#!/usr/bin/bash
set -euo pipefail
export PATH=/usr/sbin:/usr/bin
umask 077

fail() {
    printf '%s\n' "$*" >&2
    exit 1
}

[[ $# == 0 && $EUID == 0 ]] || fail 'Run t2-touchid-recovery-enable through pkexec, without arguments.'
module=t2_sep_transport_trial
bridge=kait2en-t2-touchid.service
kernel=$(uname -r)
file=/usr/lib/t2-touchid-recovery/modules/$kernel/$module.ko
[[ -f $file ]] || fail "No recovery driver for the running kernel: $kernel"

cmdline=" $(</proc/cmdline) "
[[ $cmdline == *' module_blacklist=t2_sep_transport '* &&
   $cmdline == *' nohibernate '* &&
   $cmdline == *' sysctl.kernel.kexec_load_disabled=1 '* ]] ||
    fail 'Boot with the Touch ID recovery test options before activating the driver.'
[[ $(</sys/power/disk) == '[disabled]' && $(</sys/power/mem_sleep) == *'[deep]'* ]] ||
    fail 'The recovery trial requires deep sleep with hibernation disabled.'
[[ $(</proc/sys/kernel/kexec_load_disabled) == 1 &&
   $(</sys/kernel/kexec/loaded) == 0 && $(</sys/kernel/kexec/crash_loaded) == 0 ]] ||
    fail 'A replacement kernel can still be loaded or is already loaded.'

exec 9>/run/t2-keybag-trial.lock
flock -n 9 || fail 'Another Touch ID recovery operation is running.'
[[ ! -d /sys/module/t2_sep_transport && ! -d /sys/module/$module && ! -e /dev/t2-aks ]] ||
    fail 'A Touch ID transport is already loaded. Shut down before switching drivers.'
sep_devices=()
for device in /sys/bus/pci/devices/*; do
    if [[ $(<"$device/vendor") == 0x106b && $(<"$device/device") == 0x1802 ]]; then
        sep_devices+=("$device")
    fi
done
[[ ${#sep_devices[@]} == 1 ]] || fail 'Expected exactly one Apple T2 SEP PCI device.'
iommu_type=${sep_devices[0]}/iommu_group/type
[[ -r $iommu_type && $(<"$iommu_type") == identity ]] ||
    fail 'Deep sleep requires the SEP to use an identity-mapped IOMMU group.'
macos_uid=$(/usr/libexec/t2-touchid-recovery/unlock --check-uid)
systemctl is-active --quiet "$bridge" || fail 'KaiT2en is not running.'
printf 'Checking KaiT2en recovery protocol support...\n'
deadline=$((SECONDS + 30))
while :; do
    invocation=$(systemctl show "$bridge" --property=InvocationID --value)
    if [[ -n $invocation && -n $(journalctl -q -b -u "$bridge" -o cat -n 1 \
        "_SYSTEMD_INVOCATION_ID=$invocation" \
        --grep='^t2-touchid: Touch ID recovery lockout protocol uid-v1$') ]]; then
        break
    fi
    (( SECONDS < deadline )) ||
        fail 'The running KaiT2en bridge did not report UID-tagged lockout support. The recovery driver has not started.'
    sleep 1
done

runtime=/run/t2-touchid-recovery
install -d -m 0700 -- "$runtime"
insmod "$file" register_ool=1 probe_capabilities=1 allow_deep_sleep=1
shopt -s nullglob
devices=(/sys/bus/pci/drivers/"$module"/????:??:??.?)
[[ ${#devices[@]} == 1 && -w ${devices[0]}/activate ]] || fail 'The recovery driver did not bind to one SEP device.'
sep=${devices[0]}

source /usr/libexec/t2-touchid-recovery/service-guard
trap 'resume_touchid || exit 1' EXIT
trap 'exit 130' HUP INT TERM
pause_touchid
if ! printf '1\n' >"$sep/activate" ||
    [[ ! -c /dev/t2-aks || ! "$sep" -ef /sys/class/misc/t2-aks/device ]]; then
    fail 'Touch ID recovery activation failed. Shut down fully before trying again.'
fi
printf '%s\n' "$macos_uid" >"$runtime/active-uid"
printf 'Touch ID recovery driver is ready.\n'
