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

keybag=/usr/bin/t2-touchid-keybag
guide=/usr/share/doc/t2-touchid-setup/README.fedora.md
folder=T2-Recovery
encrypted=t2-touchid-keybag.p7m

usage() {
    printf '%s\n' 'Usage: t2-touchid-setup [prepare | import | import-existing | enable]' \
        'Run without arguments for the interactive menu.' "Guide: $guide"
}

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

prepare_usb() (
    local mount transfer stage digest
    printf '%s\n' 'Mount a USB drive that both Fedora and macOS can write to.'
    IFS= read -er -p 'Mounted USB path (for example /run/media/you/USB): ' mount || exit 1
    if [[ $mount != /* || ! -w $mount ]] || ! mountpoint -q -- "$mount"; then
        fail 'Enter the full path to a mounted, writable USB volume.'
    fi
    transfer=${mount%/}/$folder
    [[ ! -e $transfer && ! -L $transfer ]] ||
        fail "$transfer already exists. Use it for the current transfer or move it aside to start over."

    stage=$(mktemp -d -- "${mount%/}/.t2-touchid-setup.XXXXXXXX")
    trap 'rm -f -- "$stage/recipient.pem" "$stage/t2-touchid-keybag"; rmdir -- "$stage"' EXIT
    trap 'exit 130' HUP INT TERM
    # pkexec reads the private state; the desktop user writes to the USB drive.
    pkexec "$keybag" init >"$stage/recipient.pem"
    digest=$(sha256sum <"$keybag")
    cp -- "$keybag" "$stage/t2-touchid-keybag"
    mv -nT -- "$stage" "$transfer"
    [[ ! -e $stage ]] || fail "$transfer already exists."
    trap - EXIT HUP INT TERM

    printf '\nFiles are ready in %s.\n' "$transfer"
    printf 'Exporter SHA-256: %s\n' "${digest%% *}"
    # shellcheck disable=SC2016
    printf '%s\n' \
        'Save the certificate fingerprint and exporter SHA-256 separately from the USB drive.' \
        'Eject the USB drive. Shut the Mac down, then start macOS.' \
        'Sign in to the account that owns the fingerprint and open Terminal.' \
        'Run these commands, replacing USB with the volume name. Do not use sudo.' \
        "  transfer=\"/Volumes/USB/$folder\"" \
        '  exporter=$(mktemp "${TMPDIR:-/tmp}/t2-touchid-export.XXXXXXXX")' \
        '  cp "$transfer/t2-touchid-keybag" "$exporter" && shasum -a 256 "$exporter"' \
        'If the hash matches the exporter SHA-256 saved on Fedora, run:' \
        '  bash "$exporter" export "$transfer"' \
        '  rm -f "$exporter"' \
        'Record the macOS UID and encrypted keybag SHA-256 that the exporter prints.' \
        'Eject the drive, shut down, and start Fedora. Run t2-touchid-setup import.'
)

import_keybag() {
    local input uid digest
    printf '%s\n' 'Mount the transfer drive and have the UID and SHA-256 from macOS ready.'
    IFS= read -er -p "Full path to $encrypted: " input || exit 1
    [[ $input == /* ]] || fail 'Enter the full path to the encrypted keybag.'
    read -r -p 'macOS UID: ' uid || exit 1
    [[ $uid =~ ^[1-9][0-9]{0,8}$ ]] || fail 'Enter the numeric UID printed by the exporter.'
    read -r -p 'Encrypted keybag SHA-256: ' digest || exit 1
    [[ $digest =~ ^[0-9A-Fa-f]{64}$ ]] || fail 'Enter the 64-digit SHA-256 printed by the exporter.'
    pkexec "$keybag" import "$uid" "$digest" "$input"
    printf '%s\n' 'Eject the drive. To prepare for a test boot, run t2-touchid-setup enable.'
}

import_existing() (
    local input uid account legacy keys='' temp digest
    printf '%s\n' \
        'Use a user.kb from this Mac, an older encrypted backup, or the installed trial keybag.' \
        'Use import instead for a keybag exported by t2-touchid-setup.' \
        'Use the UID and GeneratedUID from the account that owns the fingerprint.' \
        "On macOS, run: dscl . -read \"/Users/\$(id -un)\" UniqueID GeneratedUID"
    IFS= read -er -p 'Full path to the existing keybag (Enter for the installed trial keybag): ' input || exit 1
    [[ -z $input || ( $input == /* && -f $input && -r $input ) ]] ||
        fail 'Enter the full path to a readable keybag.'
    read -r -p 'macOS UID (UniqueID): ' uid || exit 1
    [[ $uid =~ ^[1-9][0-9]{0,8}$ ]] || fail 'Enter the numeric macOS account UID.'
    read -r -p 'macOS account UUID (GeneratedUID): ' account || exit 1
    [[ $account =~ ^[0-9A-Fa-f]{8}(-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}$ ]] ||
        fail 'Enter the GeneratedUID of the macOS account.'
    if [[ -z $input ]]; then
        pkexec "$keybag" migrate "$uid" "$account"
        return
    fi
    read -r -p 'Is this an older encrypted backup? [y/N] ' legacy || exit 1
    if [[ $legacy == [yY] || $legacy == [yY][eE][sS] ]]; then
        IFS= read -er -p 'Folder containing the original key.pem and recipient.pem: ' keys || exit 1
        [[ $keys == /* && -r $keys/key.pem && -r $keys/recipient.pem ]] ||
            fail 'Enter the full path to the folder with both original files.'
    fi

    umask 077
    ulimit -c 0
    temp=$(mktemp -d)
    trap 'rm -f -- "$temp/recipient.pem" "$temp/$encrypted"; rmdir -- "$temp"' EXIT
    trap 'exit 130' HUP INT TERM
    pkexec "$keybag" init >"$temp/recipient.pem"
    if [[ -n $keys ]]; then
        # Pipe the decrypted backup directly into the new encrypted export.
        openssl smime -decrypt -binary -inform DER -in "$input" \
            -recip "$keys/recipient.pem" -inkey "$keys/key.pem" |
            "$keybag" seal "$uid" "$account" "$temp/recipient.pem" >"$temp/$encrypted"
    else
        "$keybag" seal "$uid" "$account" "$temp/recipient.pem" <"$input" >"$temp/$encrypted"
    fi
    digest=$(sha256sum <"$temp/$encrypted")
    pkexec "$keybag" import "$uid" "${digest%% *}" "$temp/$encrypted"
    printf '%s\n' 'To prepare for a test boot, run t2-touchid-setup enable.'
)

enable_recovery() {
    local answer
    printf '%s\n' \
        'Use the matching Fedora kernel and a KaiT2en bridge with UID-tagged lockout support.' \
        'After a full shutdown, start Fedora with these options for the test boot:' \
        '  module_blacklist=t2_sep_transport nohibernate sysctl.kernel.kexec_load_disabled=1 mem_sleep_default=deep' \
        'Stop any earlier trial notifier and run this from your Plasma session.' \
        'After attempting activation, use Shut Down. Warm restart is unverified.'
    read -r -p 'Enable Touch ID recovery for this boot? [y/N] ' answer || exit 1
    [[ $answer == [yY] || $answer == [yY][eE][sS] ]] || return 0
    systemctl --user show-environment >/dev/null ||
        fail 'Open a terminal in your Plasma session and try again.'
    [[ -n $(journalctl -q -b -u kait2en-t2-touchid.service -o cat -n 1 \
        --grep='^t2-touchid: Touch ID recovery lockout protocol uid-v1$') ]] ||
        fail 'Your desktop user must be able to read the KaiT2en journal for this boot. Check journal access and the bridge version.'
    pkexec /usr/bin/t2-touchid-recovery-enable
    systemctl --user start t2-touchid-recovery-notify.service ||
        fail 'The driver is active, but the notification failed to start. Run systemctl --user start t2-touchid-recovery-notify.service to retry.'
    printf '%s\n' 'After a lockout, choose Unlock Touch ID and enter your macOS login password.'
}

(( $# <= 1 )) || { usage >&2; exit 2; }
case ${1:-} in
    -h|--help) usage; exit 0 ;;
    ''|prepare|import|import-existing|enable) ;;
    *) usage >&2; exit 2 ;;
esac
[[ -t 0 && -t 1 && $EUID != 0 ]] ||
    fail 'Run t2-touchid-setup in a terminal as your Fedora desktop user. See t2-touchid-setup --help.'

step=${1:-}
if [[ -z $step ]]; then
    printf 'Experimental Touch ID setup\nGuide: %s\n\n' "$guide"
    printf '%s\n' 'For a new export, choose prepare first. If you have a backup, choose import-existing.'
    PS3='Choose a step: '
    select step in prepare import import-existing enable quit; do
        [[ -n $step ]] && break
        printf '%s\n' 'Choose a number from 1 to 5.' >&2
    done
fi

case $step in
    prepare) prepare_usb ;;
    import) import_keybag ;;
    import-existing) import_existing ;;
    enable) enable_recovery ;;
    quit) exit 0 ;;
esac
