#!/bin/sh
# /usr/libexec/ctg-azkaban/tmpool-ensure  (azkaban host)
# Make the USB-backed pool "tmpool" healthy and start the Time Machine CT (109).
# Run by tmpool-ensure.service at boot (Type=simple, never blocks boot) and by udev when the
# disk (re)appears. Bounded: gives up after ~3 min if the disk is absent. Silent unless it acts.
POOL=tmpool
DEV=/dev/disk/by-id/ata-PC811_SED_SK_hynix_2048GB_AME6N008111706O5D
CT=109
exec 9>/run/tmpool-ensure.lock; flock -n 9 || exit 0
tag() { logger -t tmpool-ensure "$*"; }
i=0
while [ $i -lt 36 ]; do
	[ -e "$DEV" ] && break
	i=$((i+1)); sleep 5
done
[ -e "$DEV" ] || { tag "disk absent, giving up (pool stays offline, CT $CT not started)"; exit 0; }
if ! zpool list -H -o name $POOL >/dev/null 2>&1; then
	zpool import -d /dev/disk/by-id $POOL && tag "imported $POOL"
else
	zpool online $POOL $DEV >/dev/null 2>&1
	zpool clear $POOL >/dev/null 2>&1
fi
zfs load-key -a 2>/dev/null; zfs mount -a 2>/dev/null
if zpool list -H -o health $POOL 2>/dev/null | grep -q ONLINE; then
	if [ "$(pct status $CT 2>/dev/null)" = "status: stopped" ]; then
		pct start $CT && tag "started CT $CT"
	fi
fi
exit 0
