#!/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}"
		[ -n "${MBD_BACKUP}" ] || _exit "Please provide a backup archive."
		MBD_HOME="$(getent passwd mini-buildd | cut -d: -f6)"
		[ -n "${MBD_HOME}" ] || _exit "No mini-buildd home found.\nPlease do a (fresh) installation of mini-buildd.deb here to restore."

		read -e -i "n" -p "Restore '${MBD_BACKUP}' -- DANGER: will unpack in / and happily overwrite (Y/n)? " ANSWER
		if [ "${ANSWER}" = "Y" ]; then
			service mini-buildd stop
			tar --directory / --extract --file "${MBD_BACKUP}"
		fi
		;;
	*)
		_exit "Wrong usage."
		;;
esac
