#!/bin/sh

set -e

. /usr/share/debconf/confmodule

_FILE="/etc/live/autobuild.d/manual.conf"

case "${1}" in
	configure)
		db_get live-autobuild-manual/enable
		LIVE_AUTOBUILD_MANUAL="${RET}" # boolean

		db_get live-autobuild-manual/username
		_USERNAME="${RET:-live-autobuild-manual}" # string (w/o empty)

		db_get live-autobuild-manual/directory
		LIVE_AUTOBUILD_MANUAL_DIRECTORY="${RET:-/srv/debian.net/live/cdimage}" # string (w/o empty)

		db_get live-autobuild-manual/cron
		_CRON="${RET}" # string (w empty)

		db_stop

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

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

cat > "${_FILE}" << EOF
# /etc/live/autobuild.d/manual.conf

LIVE_AUTOBUILD_MANUAL="${LIVE_AUTOBUILD_MANUAL}"
LIVE_AUTOBUILD_MANUAL_DIRECTORY="${LIVE_AUTOBUILD_MANUAL_DIRECTORY}"

export LIVE_AUTOBUILD_MANUAL LIVE_AUTOBUILD_MANUAL_DIRECTORY
EOF

		fi

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

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

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

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

		sed	-e "s|^ *LIVE_AUTOBUILD_MANUAL=.*|LIVE_AUTOBUILD_MANUAL=\"${LIVE_AUTOBUILD_MANUAL}\"|" \
			-e "s|^ *LIVE_AUTOBUILD_MANUAL_DIRECTORY=.*|LIVE_AUTOBUILD_MANUAL_DIRECTORY=\"${LIVE_AUTOBUILD_MANUAL_DIRECTORY}\"|" \
		"${_FILE}" > "${_FILE}.tmp"

		mv -f "${_FILE}.tmp" "${_FILE}"

		if ! getent passwd "${_USERNAME}"
		then
			adduser --quiet --system --home ${LIVE_AUTOBUILD_MANUAL_DIRECTORY} --shell /bin/sh --disabled-password --no-create-home --gecos 'live-autobuild-manual' --group ${_USERNAME}
		elif ! getent group "${_USERNAME}"
		then
			addgroup --system --quiet ${_USERNAME}
			gpasswd -a ${_USERNAME} ${_USERNAME}
		fi

		mkdir -p "${LIVE_AUTOBUILD_MANUAL_DIRECTORY}"
		chown ${_USERNAME}:${_USERNAME} "${LIVE_AUTOBUILD_MANUAL_DIRECTORY}" -R

		if [ -n "${_CRON}" ]
		then

cat > /etc/cron.d/live-autobuild-manual << EOF
# /etc/cron.d/live-autobuild-manual

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# m h dom mon dow	user		command
${_CRON}		${_USERNAME}	/usr/bin/live-autobuild-manual
EOF

		else
			rm -f /etc/cron.d/live-autobuild-manual
		fi

		if [ -x "/etc/init.d/cron" ]
		then
			if [ -x "$(which invoke-rc.d 2>/dev/null)" ]
			then
				invoke-rc.d cron restart || exit ${?}
			else
				/etc/init.d/cron restart || exit ${?}
			fi
		fi
		;;

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

		;;

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

#DEBHELPER#

exit 0
