#!/bin/sh
# postinst script for pistop
#
# see: dh_installdeb(1)

set -e
prefix=/usr
servicedir=/service
# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see https://www.debian.org/doc/debian-policy/ or
# the debian-policy package


upgrade=0
case "$1" in
    configure)
	if [ ! " $2" = " " ] ; then
		upgrade=1
	fi
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#
if [ $upgrade -eq 1 ] ; then # upgrade
	# refresh fclient, fserver services
	for i in fclient fserver update
	do
		if [ ! -d ${servicedir}/$i ] ; then
			continue
		fi
		# earlier installs did not have .options
		if [ ! -f ${servicedir}/$i/variables/.options ] ; then
			mkdir -p ${servicedir}/$i/variables
			options=`grep "^#" ${servicedir}/$i/run | sed -n 2p | cut -c3-`
			if [ -n "$options" ] ; then
				echo $options > ${servicedir}/$i/variables/.options
			fi
		fi
		set +e
		user=`getent passwd 1000|cut -d: -f1`
		grep "\--user" ${servicedir}/$i/variables/.options >/dev/null
		if [ $? -ne 0 ] ; then
			sed -i "s/--service_name=${i}/--service_name=${i} --user=${user}/" ${servicedir}/$i/variables/.options
		fi
		set -e
		${prefix}/sbin/minisvc --servicedir=${servicedir} --refreshsvc="${servicedir}/$i" --silent
		${prefix}/sbin/minisvc --servicedir=${servicedir} --service-name=$i \
			--export-variables=${servicedir}/$i/variables/.variables --force --silent
	done
	# start fclient, fserver services after upgrade
	if [ -d /run ] ; then
		rundir=/run/svscan
	elif [ -d /var/run ] ; then
		rundir=/var/run/svscan
	else
		rundir=${servicedir}
	fi
	set +e
	for i in fclient fserver update
	do
		if [ ! -d ${servicedir}/$i ] ; then
			continue
		fi
		${prefix}/bin/svok ${servicedir}/$i >/dev/null 2>&1
		if [ $? -eq 0 -a -f ${rundir}/$i/.down ] ; then
			rm -f ${rundir}/$i/.down
			${prefix}/bin/svc -u ${servicedir}/$i
		fi
	done
	set -e
	exit 0
fi
for i in fclient fserver update
do
	if [ ! -d ${servicedir}/$i ] ; then
		continue
	fi
	${prefix}/sbin/minisvc --servicedir=${servicedir} --service-name=$i \
		--export-variables=${servicedir}/$i/variables/.variables --force --silent
done
exit 0
