#!/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 'Export script SHA-256: %s\n' "${digest%% *}"
    # shellcheck disable=SC2016
    printf '%s\n' \
        'Save the certificate fingerprint and export script SHA-256 somewhere other than the USB drive.' \
        'Eject the USB drive. Shut the Mac down, then start macOS.' \
        'Sign in to the macOS account where you enrolled your fingerprint. 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 export script SHA-256 you saved on Fedora, run:' \
        '  bash "$exporter" export "$transfer"' \
        '  rm -f "$exporter"' \
        'Save the macOS UID and encrypted keybag SHA-256 somewhere other than the USB drive.' \
        'Eject the drive, shut down, and start Fedora. Run t2-touchid-setup import.'
)

import_keybag() {
    local input uid digest
    printf '%s\n' 'Mount the USB drive and have the macOS UID and encrypted keybag SHA-256 from your export 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 macOS UID printed by the export script.'
    read -r -p 'Encrypted keybag SHA-256: ' digest || exit 1
    [[ $digest =~ ^[0-9A-Fa-f]{64}$ ]] || fail 'Enter the 64-character SHA-256 printed by the export script.'
    pkexec "$keybag" import "$uid" "$digest" "$input"
    printf '%s\n' 'Eject the USB drive. Run t2-touchid-setup enable to enable Unlock Touch ID.'
}

import_existing() (
    local choice input='' uid account legacy keys='' temp digest status
    local -a sources=(
        'Reuse the keybag saved by a previous Touch ID setup on this Fedora installation'
        'Import a separate keybag file'
        'Cancel'
    )
    printf '%s\n' \
        'Unlock Touch ID uses a file from macOS called a keybag.' \
        'When setup imports that file, it keeps a copy on Fedora. If Unlock Touch ID was set up here before, choose option 1. No USB drive or file path is needed.' \
        'If you have a separate keybag file, choose option 2.' \
        'If you just exported a file to a USB drive, cancel here and run t2-touchid-setup import.' \
        'For first-time setup without a keybag, cancel here and run t2-touchid-setup prepare.'
    PS3='Choose an option: '
    select choice in "${sources[@]}"; do
        [[ -n $choice ]] && break
        printf '%s\n' 'Choose a number from 1 to 3.' >&2
    done
    case ${choice:-} in
        "${sources[0]}")
            if pkexec "$keybag" migrate; then
                return 0
            else
                status=$?
                (( status == 3 )) || return "$status"
            fi
            printf '%s\n' 'The keybag saved on Fedora uses an older format. Confirm the macOS account to update it.'
            ;;
        "${sources[1]}")
            printf '%s\n' 'Use a copy of user.kb from macOS, or an encrypted backup with its original key.pem and recipient.pem files.'
            IFS= read -er -p 'Full path to the keybag file: ' input || exit 1
            [[ $input == /* && -f $input && -r $input ]] ||
                fail 'Enter the full path to a readable keybag file.'
            ;;
        "${sources[2]}") return 0 ;;
        *) return 1 ;;
    esac
    printf '%s\n' \
        'Fedora checks that the file belongs to the macOS account where you set up Touch ID. It needs two account IDs from macOS: UniqueID and GeneratedUID.' \
        "In macOS Terminal, run: dscl . -read \"/Users/\$(id -un)\" UniqueID GeneratedUID"
    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 encrypted backup that came with key.pem and recipient.pem? [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' 'Run t2-touchid-setup enable to enable Unlock Touch ID.'
)

enable_unlock() {
    local answer
    printf '%s\n' \
        'Run this from a terminal in KDE Plasma. Fedora will ask for administrator authentication.' \
        'Hibernation is unavailable while Unlock Touch ID is active.'
    read -r -p 'Enable Unlock Touch ID now and after restart? [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.'
    pkexec /usr/bin/t2-touchid-recovery-enable --persistent
    source /usr/libexec/t2-touchid-recovery/service-guard
    wait_touchid_protocol ||
        fail 'Startup at boot is enabled, but the notification could not confirm the running Touch ID service. Check kait2en-t2-touchid.service and your access to its system log, then run t2-touchid-setup enable again.'
    systemctl --user enable --now t2-touchid-recovery-notify.service ||
        fail 'The driver is enabled, but the notification could not be enabled. Run t2-touchid-setup enable again to retry.'
    printf '%s\n' 'Unlock Touch ID is enabled and will start when Fedora boots.'
    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 '%s\n' 'Set up Unlock Touch ID' "Guide: $guide" \
        'For first-time setup, start with prepare. When you return from macOS with the USB drive, choose import.' ''
    PS3='Choose a step: '
    select step in \
        'prepare: Start setup with a USB drive' \
        'import: Finish setup using the file exported to your USB drive' \
        'import-existing: Reuse a keybag from a previous setup or import a separate keybag file' \
        'enable: Enable Unlock Touch ID now and after restart' \
        'quit: Exit'; do
        [[ -n $step ]] && break
        printf '%s\n' 'Choose a number from 1 to 5.' >&2
    done
    step=${step%%:*}
fi

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