#!/usr/bin/bash
set -euo pipefail
ulimit -c 0

unlock_keybag() {
    local password
    if ! password=$(kdialog --title 'Unlock Touch ID' \
        --password 'Enter your macOS login password to unlock Touch ID. Fedora may ask for its own password separately.'); then
        return
    fi
    [[ -n $password ]] || return 0
    if printf '%s\n' "$password" | /usr/bin/pkexec --disable-internal-agent \
        /usr/libexec/t2-touchid-recovery/unlock --gui-stdin "$1"; then
        unset password
        notify-send --app-name='Touch ID' 'Touch ID unlocked'
    else
        unset password
        notify-send --app-name='Touch ID' 'Could not unlock Touch ID' 'Check the recovery service log before retrying.'
    fi
}

last=0
suppress_through=0
lockout='^t2-touchid: T2 keybag locked; macOS password required; uid=([1-9][0-9]{0,8})$'
stdbuf -oL journalctl --follow --lines=0 --boot --unit=kait2en-t2-touchid.service \
    --grep="$lockout" --output=short-unix --no-hostname |
while IFS=' ' read -r timestamp source event; do
    [[ $event =~ $lockout ]] || continue
    macos_uid=${BASH_REMATCH[1]}
    [[ -c /dev/t2-aks && $timestamp =~ ^[0-9]+\.[0-9]{6}$ ]] || continue
    second=${timestamp%%.*}
    (( ${timestamp/./} > suppress_through && EPOCHSECONDS - second <= 5 && second - last >= 2 )) || continue
    last=$second
    reply=$(notify-send --app-name='Touch ID' --icon=dialog-password \
        --hint=string:x-kde-display-appname:'Touch ID' --urgency=critical --expire-time=0 --print-id \
        --action=unlock='Unlock Touch ID' 'Touch ID is locked' \
        'Unlock it with your macOS login password.') || reply=
    if [[ ${reply##*$'\n'} == unlock ]]; then
        notification_id=${reply%%$'\n'*}
        if [[ $notification_id =~ ^[0-9]+$ ]]; then
            busctl --user call org.freedesktop.Notifications /org/freedesktop/Notifications \
                CloseNotification u "$notification_id" >/dev/null || true
        fi
        unlock_keybag "$macos_uid"
        # The Fedora authorization prompt can generate another lockout event.
        suppress_through=${EPOCHREALTIME/./}
    fi
done
