#!/bin/sh

set -e

# create users
#DEBHELPER#

. /usr/share/debconf/confmodule

CONFFILE="/etc/beszel/hub.conf"
ID="_beszel-hub"

case "${1}" in
	configure)
		db_get beszel-hub/port
		PORT="${RET:-8090}" # string w/o empty

		db_stop

		if [ ! -e "${CONFFILE}" ]
		then

			mkdir -p "$(dirname "${CONFFILE}")"

cat > "${CONFFILE}" << EOF
# ${CONFFILE}

PORT="${PORT}"
EOF

			chown ${ID}:${ID} "${CONFFILE}"
			chmod 0640 "${CONFFILE}"
		fi

		cp -a -f "${CONFFILE}" "${CONFFILE}.tmp"

		# If the admin deleted or commented some variables but then set
		# them via debconf, (re-)add them to the config file.

		test -z "${PORT}" || \
		grep -Eq '^ *PORT=' "${CONFFILE}" || \
		echo "PORT=" >> "${CONFFILE}"

		sed -e "s|^ *PORT=.*|PORT=\"${PORT}\"|" \
		< "${CONFFILE}" > "${CONFFILE}.tmp"

		mv -f "${CONFFILE}.tmp" "${CONFFILE}"
		;;

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

		;;

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

# reload daemon
#DEBHELPER#

exit 0
