#!/bin/bash -e

DESCRIPTION="Create (or restore from) a mini-buildd backup archive."

_exit()
{
	{
		printf "E: %s\n\n" "${1}"
		${0} --help
	} >&2
	exit 1
}

_exit_no_root() { [ $(id -u) -eq 0 ] || _exit "Needs to be run as root."; }

case "${1}" in
	"--help")
		cat <<EOF
Usage: mini-buildd-backup --help|--backup|(--restore <backup_tarball>)

Only run as user root.

${DESCRIPTION}

EOF
		exit 0
		;;
	"--backup")
		_exit_no_root
		MBD_BACKUP="$(pwd)/mini-buildd-backup-$(date --rfc-3339=date).tar.xz"
		MBD_HOME="$(getent passwd mini-buildd | cut -d: -f6)"
		[ -n "${MBD_HOME}" ] || _exit "No mini-buildd home found."

		read -e -i "Y" -p "Backup from '${MBD_HOME}' to '${MBD_BACKUP}' (Y/n)? " ANSWER
		if [ "${ANSWER}" = "Y" ]; then
			service mini-buildd stop
			tar --create --file "${MBD_BACKUP}" "${MBD_HOME}" /etc/default/mini-buildd /etc/schroot/mini-buildd/ $(find "/etc/ssl/mini-buildd/" -mindepth 0 -maxdepth 0) $(find /etc/schroot/chroot.d/ -name "mini-buildd-*.conf")
		fi
		;;
	"--restore")
		_exit_no_root
		MBD_BACKUP="${2}"
		[ -e "${MBD_BACKUP}" ] || _exit "No such backup archive: ${MBD_BACKUP}"

		if getent passwd mini-buildd; then
			_exit "mini-buildd user exist. Please restore only whery mini-buildd is not installed yet (then install mini-buildd on top of that)."
		fi

		read -e -i "n" -p "Add mini-buildd user && restore '${MBD_BACKUP}' -- DANGER: will unpack in / and happily overwrite (Y/n)? " ANSWER
		if [ "${ANSWER}" = "Y" ]; then
			# Add mini-buildd user just the same way as postinstall, with debconf defaults
			MBD_HOME="/var/lib/mini-buildd"
			adduser --system --group --shell /bin/bash --home "${MBD_HOME}" --gecos "Custom Debian buildd" mini-buildd
			tar --directory / --extract --file "${MBD_BACKUP}"
		fi
		;;
	*)
		_exit "Wrong usage."
		;;
esac
