#!/bin/bash
# yk-age: thin wrapper around age that talks to a YubiKey via age-plugin-yubikey.
#
#   Encrypt (default):  yk-age [--slot N] <age args>            -> recipient from --list
#   Decrypt:            yk-age --decrypt [--slot N] <age args>  -> identity from --identity
#
# Any flag you don't use below is passed straight through to age, so `-o`,
# pipes (stdin/stdout), `-p`, etc. all keep working.
set -euo pipefail

age_plugin=age-plugin-yubikey

slot=
serial=
age_args=()

# Split our flags from age's flags, by index (a shift in a for-loop trips
# errexit). Whatever we don't consume is passed straight through to age.
args=("$@")
i=0
while [ "$i" -lt "${#args[@]}" ]; do
  a="${args[$i]}"
  case "$a" in
    --slot)
      slot="${args[$((i + 1))]:?--slot needs an argument}"; i=$((i + 2)); continue ;;
    --slot=*) slot="${a#--slot=}"; i=$((i + 1)); continue ;;
    --serial)
      serial="${args[$((i + 1))]:?--serial needs an argument}"; i=$((i + 2)); continue ;;
    --serial=*) serial="${a#--serial=}"; i=$((i + 1)); continue ;;
    *)        age_args+=("$a"); i=$((i + 1)) ;;
  esac
done

# Build the shared YubiKey selector, empty unless the user asked for one.
yk_args=()
[[ -n "$slot"   ]] && yk_args+=(--slot "$slot")
[[ -n "$serial" ]] && yk_args+=(--serial "$serial")

has_arg() { # $1 = flag, rest = args to scan
  local flag=$1; shift
  while [ $# -gt 0 ]; do
    [ "$1" = "$flag" ] && return 0
    shift
  done
  return 1
}

is_decrypt=0
has_arg -d   "${age_args[@]}" && is_decrypt=1
has_arg --decrypt "${age_args[@]}" && is_decrypt=1

if [ "$is_decrypt" -eq 1 ]; then
  # Decrypt: pull the identity out of the YubiKey and hand it to age via -i.
  # Injected flags go before the user's args so they precede any input file.
  idfile=$(mktemp)
  trap 'rm -f "$idfile"' EXIT
  $age_plugin --identity "${yk_args[@]}" >"$idfile"
  if ! has_arg -i "${age_args[@]}"; then
    age_args=("-i" "$idfile" "${age_args[@]}")
  fi
  exec age "${age_args[@]}"
else
  # Encrypt: pull the recipient(s) out of the YubiKey and hand them to age -r.
  # Injected flags go before the user's args so they precede any input file.
  if ! has_arg -r "${age_args[@]}" && ! has_arg --recipient "${age_args[@]}"; then
    recip_args=()
    while IFS= read -r recip; do
      case "$recip" in age1*) recip_args+=("-r" "$recip");; esac
    done < <($age_plugin --list "${yk_args[@]}")
    age_args=("${recip_args[@]}" "${age_args[@]}")
  fi
  exec age "${age_args[@]}"
fi
