#!/bin/sh

set -e
set -x
set -u

# Set CHECK_ONLY to a non-null value to just call ftjail check-freebsd-update
: ${CHECK_ONLY=""}

JAIL_NAME="${1:-}"

if [ -z "${JAIL_NAME}" ]; then
  echo "ERROR: No jail name given" 1>&2
  exit 2
fi



OLD_BASE_RO="dpool/jail/ttmpl/base-ro/13.2-RELEASE@p5"
NEW_BASE_RO="dpool/jail/ttmpl/base-ro/13.2-RELEASE@p9"
NEW_ETCUPDATE="/jail/RELEASE/etcupdate-current-13.2@p9.tbz"
SNAPSHOT_NAME="13.2-p5-20240108-1"

SNAPSHOT_ROOT="dpool/jail/TVAR"

BASE_DIR="/jail/TROOT"

ftjail check-freebsd-update -R "${SNAPSHOT_ROOT}/${JAIL_NAME}@${SNAPSHOT_NAME}" -o "${OLD_BASE_RO}" "${BASE_DIR}/${JAIL_NAME}" "${NEW_BASE_RO}" "${NEW_ETCUPDATE}" || exit 1

[ -n "${CHECK_ONLY}" ] && exit 0

case "${JAIL_NAME}" in
  ftp)
    zfs umount dpool/data/ftp/home-data
    ;;
  pg14)
    zfs umount dpool/pg/walarchive-db1-pg14
    zfs umount dpool/pg/data-db1-pg14
    ;;
  *)
    ;;
esac

# Snapshotting is now integrated (and checked) in "ftjail freebsd-upate"
#   zfs snapshot -r "${SNAPSHOT_ROOT}/${JAIL_NAME}@${SNAPSHOT_NAME}"

ftjail freebsd-update -R "${SNAPSHOT_ROOT}/${JAIL_NAME}@${SNAPSHOT_NAME}" -o "${OLD_BASE_RO}" "${BASE_DIR}/${JAIL_NAME}" "${NEW_BASE_RO}" "${NEW_ETCUPDATE}"

case "${JAIL_NAME}" in
  ftp)
    zfs mount dpool/data/ftp/home-data
    ;;
  pg14)
    zfs mount dpool/pg/data-db1-pg14
    zfs mount dpool/pg/walarchive-db1-pg14
    ;;
  *)
    ;;
esac
