#!/bin/sh
#
# $Id$
#

progname="$(basename $0)"

#
# Print an informational message.
#
info() {
	echo "$@"
}

#
# Print an error message to stderr and exit.
#
error() {
	echo "$progname: $@" >&2
	exit 1
}

#
# Ask a question and wait for an answer.  Keep asking until the user
# answers yes or no.
#
# Usage example:
#
#     if yesno foo ; then echo yes ; else echo no ; fi
#
yesno() {
	while :; do
		echo -n "$@ (yes/no) "
		read answer
		case $answer in
		[Yy]|[Yy][Ee][Ss])
			return 0
			;;
		[Nn]|[Nn][Oo])
			return 1
			;;
		esac
	done
}

#
# Print a usage string and exit.
#
usage() {
	echo "usage: $progname jailname [[from-release] to-release]" >&2
	exit 1
}

main() {
	case $# in
	1)
		jailname="$1"
		;;
	2)
		jailname="$1"
		fromrel="$(uname -r)"
		torel="$2"
		;;
	3)
		jailname="$1"
		fromrel="$2"
		torel="$3"
		;;
	*)
		usage
		;;
	esac


	jailroot="/jail/$jailname"
	basehash="$(echo $jailroot | sha256 -q)"
	statedir="/var/db/freebsd-update/"
	install_link="$statedir/$basehash-install"
	conffile="$jailroot/etc/freebsd-update.conf"
	if [ -n "$torel" ] ; then
		fetch="upgrade"
		relarg="-r $torel"
		pre_uname="UNAME_r=$fromrel"
		post_uname="UNAME_r=$torel"
	else
		fetch="fetch"
	fi

	if [ -n "$torel" ] ; then
		if [ -n "${QUICK_UPGRADE+yes}" ] ; then
			echo "Upgrading $jailroot from $fromrel to $torel"
		else
			yesno "Upgrade $jailroot from $fromrel to $torel?"
		fi
	else
		if [ -n "${QUICK_UPGRADE+yes}" ] ; then
			echo "Upgrading $jailroot"
		else
			yesno "Update $jailroot?"
		fi
	fi || exit 0

	if [ -n "${QUICK_UPGRADE+yes}" ] ; then
		export PAGER=cat
	fi

	set -e
	env $pre_uname freebsd-update -b "$jailroot" -d "$statedir" -f "$conffile" $relarg $fetch
	[ -d "$install_link" ] || exit 1
	env $pre_uname freebsd-update -b "$jailroot" -d "$statedir" -f "$conffile" $relarg install
	if [ -n "${QUICK_UPGRADE+yes}" ] ; then
		echo "Quick upgrade, not restarting $jailname"
	elif yesno "Restart $jailname before proceeding?" ; then
		/etc/rc.d/jail restart $jailname
	fi
	[ -d "$install_link" ] || exit 0
	env $post_uname freebsd-update -b "$jailroot" -d "$statedir" -f "$conffile" $relarg install
	[ -d "$install_link" ] || exit 0
	env $post_uname freebsd-update -b "$jailroot" -d "$statedir" -f "$conffile" $relarg install
}

main "$@"
