#!/bin/bash
# Unlock the GNOME login keyring at login using the YubiKey's FIDO2 hmac-secret
# (PIN + touch). The keyring password is stored encrypted in $DIR/password.enc;
# the key derives the decryption secret. Set up with yubikey-keyring-setup.
set -uo pipefail
. "$HOME/.local/lib/yubikey-keyring.sh"

locked() {
  [[ $(busctl --user get-property org.freedesktop.secrets \
    /org/freedesktop/secrets/collection/login org.freedesktop.Secret.Collection Locked 2>/dev/null) != "b false" ]]
}
locked || exit 0

dev=""
for _ in $(seq 20); do
  dev=$(yk_device)
  [[ -n $dev ]] && break
  sleep 0.5
done
if [[ -z $dev ]]; then
  notify-send -i dialog-password "Keyring" "YubiKey not found — keyring stays locked" || true
  exit 1
fi

for attempt in 1 2; do
  locked || exit 0   # unlocked meanwhile (e.g. by the normal prompt)
  secret=$(yk_secret "$dev" pin) || exit 1   # PIN dialog cancelled
  if [[ -n $secret ]]; then
    openssl enc -d -aes-256-cbc -pbkdf2 -iter 200000 -in "$DIR/password.enc" -pass fd:3 3< <(printf '%s' "$secret") \
      | "$HOME/.local/bin/keyring-unlock-dbus" && exit 0
    unset secret
    notify-send -i dialog-error "Keyring" "Unlock failed — the stored password may be out of date (re-run yubikey-keyring-reset)" || true
    exit 1
  fi
  notify-send -i dialog-error "Keyring" "Wrong PIN or no touch — try again" || true
done
exit 1
