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

state=/var/lib/t2-touchid-recovery
tools=/usr/libexec/t2-touchid-recovery
runtime=/run/t2-touchid-recovery
tool=$tools/t2-aks-tool
bridge=kait2en-t2-touchid.service
work=
gui=0
password=

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

decrypt_keybag() {
    openssl smime -decrypt -binary -inform DER -in "$imported/keybag.p7m" \
        -recip "$state/recipient/recipient.pem" -inkey "$state/recipient/key.pem"
}

cleanup() {
    local rc=$?
    unset password
    rm -f -- "$work"/{account,expected,alias,loaded,bound,after,before.der,after.der} || rc=1
    rmdir -- "$work" || rc=1
    resume_touchid || rc=1
    exit "$rc"
}

report_state() {
    local stage=$1 handle=$2 output=$work/$1.der
    rm -f -- "$output" || return 1
    "$tool" get-device-state-v1 1 "$handle" 0 "$output" >/dev/null || return 1
    python3 -IB - "$tools" "$output" "$handle" "$stage" "$work/account" <<'PY'
import sys
from pathlib import Path
from uuid import UUID

sys.path.insert(0, sys.argv[1])
from t2_aks_state import decode

state = decode(Path(sys.argv[2]).read_bytes())
if state.handle != int(sys.argv[3]):
    sys.exit("AppleKeyStore returned the wrong keybag handle.")
if UUID(state.user_uuid).bytes != Path(sys.argv[5]).read_bytes():
    sys.exit("AppleKeyStore returned a keybag state for a different macOS account.")
print(f"AppleKeyStore lock state {sys.argv[4]}: {state.lock_state:#06x}")
# Keep these masks aligned with the pinned t2_user_readiness.py classifier.
known = 0x06ff
blocked = 0x00d7
if state.lock_state & ~known:
    sys.exit("AppleKeyStore returned an unknown lock state.")
if sys.argv[4] == "before":
    if state.lock_state & 0x82:
        sys.exit("AppleKeyStore reports password lockout or corruption. No password was sent.")
    if not state.lock_state & 0x55:
        sys.exit(3)
elif state.lock_state & blocked:
    sys.exit("AppleKeyStore still reports a locked keybag.")
PY
}

ask_password() {
    local LC_ALL=C
    if (( gui )); then
        IFS= read -r -t 120 -n 129 password || fail 'No complete macOS password was received.'
    else
        password=$(systemd-ask-password --timeout=120 --echo=no 'macOS login password for Touch ID:') ||
            fail 'No macOS password was received.'
    fi
    [[ -n $password && ${#password} -le 128 && $password != *$'\r'* && $password != *$'\n'* ]] ||
        fail 'The macOS password must be 1 to 128 bytes.'
}

try_unlock() {
    local normal= result alias_present=true normal_locked=false special_locked=false
    if "$tool" copy-keybag-uuid 1 "$special" "$work/alias" >/dev/null; then
        cmp -s -- "$work/expected" "$work/alias" || fail 'The live keybag does not match the imported keybag.'
    else
        [[ $? == 3 ]] || fail 'Could not determine whether this account has a live keybag.'
        alias_present=false
    fi

    # Keep the normal handle for retries in this boot, but verify it with the
    # SEP each time. Never put another keybag's handle in an unlock request.
    if [[ -s $runtime/normal-handle ]]; then
        normal=$(<"$runtime/normal-handle")
        if [[ $normal =~ ^[1-9][0-9]{0,9}$ ]] && (( normal <= 2147483647 )); then
            if "$tool" copy-keybag-uuid 1 "$normal" "$work/loaded" >/dev/null; then
                cmp -s -- "$work/expected" "$work/loaded" || normal=
                rm -f -- "$work/loaded"
            else
                [[ $? == 3 ]] || fail 'Could not check the previously loaded keybag.'
                normal=
            fi
        else
            normal=
        fi
    fi
    if [[ -z $normal ]]; then
        result=$(decrypt_keybag | "$tools/keybag-uuid" "$macos_uid" --load) ||
            fail 'AppleKeyStore did not load the keybag.'
        [[ $result =~ ^status=0[[:space:]]handle=([1-9][0-9]{0,9})[[:space:]]response_length=[0-9]+$ ]] ||
            fail 'AppleKeyStore did not return a valid keybag handle.'
        normal=${BASH_REMATCH[1]}
        (( normal <= 2147483647 )) || fail 'AppleKeyStore returned an out-of-range keybag handle.'
        "$tool" copy-keybag-uuid 1 "$normal" "$work/loaded" >/dev/null
        cmp -s -- "$work/expected" "$work/loaded" || fail 'The loaded keybag did not match the import.'
        printf '%s\n' "$normal" >"$runtime/normal-handle"
    fi
    if ! "$alias_present"; then
        "$tool" set-system-keybag 1 "$normal" "$special" >/dev/null
    fi
    "$tool" copy-keybag-uuid 1 "$special" "$work/bound" >/dev/null
    cmp -s -- "$work/expected" "$work/bound" || fail 'The live keybag does not match the loaded keybag.'

    if report_state before "$normal"; then
        normal_locked=true
    else
        [[ $? == 3 ]] || fail 'Could not verify the normal keybag state. No password was sent.'
    fi
    if report_state before "$special"; then
        special_locked=true
    else
        [[ $? == 3 ]] || fail 'Could not verify the account keybag state. No password was sent.'
    fi
    if "$normal_locked" && "$special_locked"; then
        printf '%s\n' "$password" | "$tool" unlock-keybags-stdin 1 "$normal" "$special"
    elif "$normal_locked"; then
        printf '%s\n' "$password" | "$tool" unlock-keybag-stdin 1 "$normal"
    elif "$special_locked"; then
        printf '%s\n' "$password" | "$tool" unlock-keybag-stdin 1 "$special"
    else
        printf 'Touch ID is already unlocked. No password was sent.\n'
        return 0
    fi
    unset password
    "$tool" copy-keybag-uuid 1 "$special" "$work/after" >/dev/null
    cmp -s -- "$work/expected" "$work/after" || fail 'The live keybag changed during unlock.'
    report_state after "$normal"
    report_state after "$special"
    printf 'AppleKeyStore accepted the password.\n'
}

[[ $EUID == 0 ]] || fail 'Run through pkexec.'
[[ -d $state/keybag ]] || fail 'Import your macOS keybag first.'
# Open the directory once so a replacement cannot pair different imports.
exec {import_fd}<"$state/keybag"
imported=/proc/$$/fd/$import_fd
[[ -s $imported/macos-uid && -s $imported/keybag.p7m ]] || fail 'The imported keybag is incomplete.'
macos_uid=$(<"$imported/macos-uid")
[[ $macos_uid =~ ^[1-9][0-9]{0,8}$ ]] || fail 'Expected a macOS account UID.'
special=-$macos_uid

if [[ $# == 1 && ( $1 == --check || $1 == --check-uid ) ]]; then
    decrypt_keybag | "$tools/keybag-uuid" "$macos_uid" >/dev/null
    if [[ $1 == --check-uid ]]; then
        printf '%s\n' "$macos_uid"
    else
        printf 'The imported keybag passed local checks. No T2 operations ran.\n'
    fi
    exit 0
fi
if [[ $# == 2 && $1 == --gui-stdin && -p /dev/stdin ]]; then
    [[ $2 == "$macos_uid" ]] || fail 'The lockout account does not match the imported keybag.'
    gui=1
elif [[ $# != 0 || ! -t 0 || ! -t 1 ]]; then
    fail 'Run through pkexec from an interactive terminal, or use Unlock Touch ID.'
fi

[[ -f $runtime/active-uid && $(<"$runtime/active-uid") == "$macos_uid" ]] ||
    fail 'Activate the packaged Touch ID recovery driver with the selected keybag first.'
ask_password
exec 9>/run/t2-keybag-trial.lock
flock -n 9 || fail 'Another Touch ID recovery operation is running.'
driver=/sys/class/misc/t2-aks/device/driver
[[ -c /dev/t2-aks && -L $driver && $(readlink -f "$driver") == */t2_sep_transport_trial ]] ||
    fail 'Activate the Touch ID recovery driver first.'
systemctl is-active --quiet "$bridge" || fail 'KaiT2en is not active.'
[[ $(findmnt -n -o FSTYPE /run) == tmpfs ]] || fail '/run is not RAM-backed.'

source "$tools/service-guard"
work=$(mktemp -d /run/t2-touchid-recovery.XXXXXXXX)
trap cleanup EXIT
trap 'exit 130' HUP INT TERM
decrypt_keybag | "$tools/keybag-uuid" "$macos_uid" --account-out "$work/account" >"$work/expected"

pause_touchid
"$tool" capabilities
try_unlock
