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

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

[[ $EUID == 0 ]] || fail 'Run t2-touchid-setup enable as your Fedora desktop user.'
if [[ $# == 1 && $1 == --persistent ]]; then
    unit=t2-touchid-unlock.service
    systemctl daemon-reload
    if ! systemctl restart "$unit"; then
        journalctl -q -b -u "$unit" -o cat -n 12 --no-pager
        fail 'Could not enable Unlock Touch ID.'
    fi
    systemctl enable "$unit"
    exit 0
fi
[[ $# == 0 ]] || fail 'Run t2-touchid-setup enable as your Fedora desktop user.'

module=t2_sep_transport_trial
bridge=kait2en-t2-touchid.service
runtime=/run/t2-touchid-recovery
kernel=$(uname -r)
file=/usr/lib/t2-touchid-recovery/modules/$kernel/$module.ko
[[ -f $file ]] || fail "Unlock Touch ID does not support the running kernel: $kernel. See the setup guide for the supported kernel."

# A crash kernel skips the driver's shutdown callback. A reservation cannot
# grow after boot, so test it even when kdump has not loaded a kernel yet.
if ! read -r crash_size </sys/kernel/kexec/crash_size ||
    ! read -r crash_loaded </sys/kernel/kexec/crash_loaded; then
    fail 'Could not check whether kdump is using reserved memory. Wait a moment and try again.'
fi
[[ $crash_size == 0 && $crash_loaded == 0 ]] ||
    fail 'Unlock Touch ID cannot run on a boot with memory reserved for kdump (kernel crash dumps).'

exec 9>/run/t2-keybag-trial.lock
flock -n 9 || fail 'Touch ID setup or unlock is already running. Wait for it to finish and try again.'

macos_uid=$(/usr/libexec/t2-touchid-recovery/unlock --check-uid)
source /usr/libexec/t2-touchid-recovery/service-guard
clear_touchid_guards || fail 'Could not clear the temporary Touch ID service settings.'
# Start it directly so this unit has no ordering dependency on the services
# it needs to stop and start again while setting up the Secure Enclave.
systemctl start "$bridge" ||
    fail 'Could not start the Touch ID service. Check systemctl status kait2en-t2-touchid.service.'
printf 'Checking whether the Touch ID service supports Unlock Touch ID...\n'
wait_touchid_protocol ||
    fail 'The running Touch ID service did not confirm support for Unlock Touch ID. Update t2-touchid and restart kait2en-t2-touchid.service before trying again.'

# A previous version could have already enabled the driver in this boot.
if [[ -f $runtime/active-uid && $(<"$runtime/active-uid") == "$macos_uid" &&
      -c /dev/t2-aks && /sys/class/misc/t2-aks/device/driver -ef /sys/bus/pci/drivers/$module ]]; then
    printf 'Unlock Touch ID is already active.\n'
    exit 0
fi
[[ ! -d /sys/module/t2_sep_transport && ! -d /sys/module/$module && ! -e /dev/t2-aks ]] ||
    fail 'A Touch ID driver is already loaded. Restart Fedora before trying again.'

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 'Could not identify a single Apple T2 Secure Enclave on this Mac.'
[[ ! -L ${sep_devices[0]}/driver ]] ||
    fail 'Another driver is using the Apple T2 Secure Enclave. Restart with that driver disabled.'

install -d -m 0700 -- "$runtime"
trap 'resume_touchid || exit 1' EXIT
trap 'exit 130' HUP INT TERM
pause_touchid
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 driver could not connect to the Apple T2 Secure Enclave.'
sep=${devices[0]}

if ! printf '1\n' >"$sep/activate" ||
    [[ ! -c /dev/t2-aks || ! "$sep" -ef /sys/class/misc/t2-aks/device ]]; then
    fail 'Could not enable Unlock Touch ID. Restart Fedora before trying again.'
fi
printf '%s\n' "$macos_uid" >"$runtime/active-uid"
resume_touchid ||
    fail 'The driver is active, but the Touch ID services could not be restarted. Run t2-touchid-setup enable again.'
trap - EXIT
wait_touchid_protocol ||
    fail 'The driver is active, but the restarted Touch ID service did not confirm support for Unlock Touch ID.'
printf 'Unlock Touch ID is active.\n'
