#!/bin/sh

err() {
	echo "${*}" >&2
	exit 1
}

format_version() {
	echo ${1} 2>/dev/null \
		| sed 's/^\([0-9\.]*\)-\(.\)[^\-]*-*p*\([0-9]*\)$/\1\2\3/'
}

nullmount() {
	mount_nullfs "${1}" "${2}/${1}"
}

bectl check \
	|| err "ZFS Boot Environments is not supported on this system."

[ -n "${1}" ] \
	|| err "You should provide new version"

: ${TMPDIR:-/tmp}

cur="$(bectl list -H | awk -F\t '$3 == "/" {print $1}')"
new="$(format_version "${1}")"
mountpoint="${TMPDIR}/be-${new}"

echo "${cur}->${new}"

# bectl create -r -e "${cur}" "${new}"
# bectl mount "${new}" "${mountpoint}"
for i in "/root" "/var/audit" "/var/backups" "/var/cache/pkg" "/var/crash" "/var/db/freebsd-update" "/var/log" "/var/tmp"; do
	nullmount "${i}" "${mountpoint}"
done
chroot "${mountpoint}" /bin/sh <<-__EOD__
	mount -t devfs devfs /dev
	# rm -R /var/db/freebsd-update/*
	# freebsd-update upgrade -r "${1}"
	# freebsd-update install  # KERNEL
	# freebsd-update install  # BASE
	# pkg bootstrap -f
	pkg update
	pkg upgrade -f -y
__EOD__
for i in "/dev" "/root" "/var/audit" "/var/backups" "/var/cache/pkg" "/var/crash" "/var/db/freebsd-update" "/var/log" "/var/tmp"; do
	umount "${mountpoint}/${i}"
done
# bectl activate "${new}"

echo
echo "========================================="
echo "/!\\ You have to update bootcode manually:"
gpart show | awk '/^=>[[:blank:]]+/{print $4, $5}' | while read dev typ; do
	fboot="$(gpart show "${dev}" | awk '/[[:blank:]]+freebsd-boot[[:blank:]]+/{print $3}')"
	str="gpart bootcode -b /boot/"
	case "${typ}" in
		(GPT)
			str="${str}pmbr"
			if [ -n "${fboot}" ]; then
				str="${str} -p /boot/gptzfsboot -i ${fboot}"
			fi
			;;
		(MBR)
			str="${str}mbr"
			if [ -n "${fboot}" ]; then
				str="${str} -p /boot/zfsboot -i ${fboot}"
			fi
			;;
		(*) str="" ;;
	esac
	str="${str} ${dev}"
	if [ "${str}" != " ${dev}" ]; then
		echo "${str}"
	fi
done
echo
