#!/usr/bin/env bash
# Write ~/.ssh/id_ed25519 for AUR pushes from CI or local scripts.
#
# Supported GitLab CI variables (pick one):
#   AUR_SSH_PRIVATE_KEY_B64  — base64 of the private key (Variable type, one line; Masked OK)
#                              or File type whose contents are that base64 string
#   AUR_SSH_PRIVATE_KEY      — raw OpenSSH private key (File type preferred), or raw key text
#                              File contents may also be base64 (auto-detected)
set -euo pipefail

KEY_PATH="${1:-$HOME/.ssh/id_ed25519}"

install -d -m 700 "$(dirname "$KEY_PATH")"

is_raw_ssh_key() {
  grep -qE 'BEGIN (OPENSSH |RSA |EC )?PRIVATE KEY' "$1" 2>/dev/null
}

decode_b64_to_key() {
  local src="$1"
  if [[ -f "$src" ]]; then
    # GitLab File variable: env value is a path to a temp file
    tr -d '\r\n[:space:]' < "$src" | base64 -d > "$KEY_PATH"
  else
    # Variable type: env value is the base64 string itself
    printf '%s' "$src" | tr -d '\r\n[:space:]' | base64 -d > "$KEY_PATH"
  fi
}

if [[ -n "${AUR_SSH_PRIVATE_KEY_B64:-}" ]]; then
  decode_b64_to_key "$AUR_SSH_PRIVATE_KEY_B64"
elif [[ -n "${AUR_SSH_PRIVATE_KEY:-}" && -f "${AUR_SSH_PRIVATE_KEY}" ]]; then
  if is_raw_ssh_key "$AUR_SSH_PRIVATE_KEY"; then
    cp "$AUR_SSH_PRIVATE_KEY" "$KEY_PATH"
  else
    # File variable mistakenly filled with base64 instead of raw PEM
    decode_b64_to_key "$AUR_SSH_PRIVATE_KEY"
  fi
elif [[ -n "${AUR_SSH_PRIVATE_KEY:-}" ]]; then
  if printf '%s' "$AUR_SSH_PRIVATE_KEY" | grep -qE 'BEGIN (OPENSSH |RSA |EC )?PRIVATE KEY'; then
    printf '%s\n' "$AUR_SSH_PRIVATE_KEY" > "$KEY_PATH"
  else
    decode_b64_to_key "$AUR_SSH_PRIVATE_KEY"
  fi
elif [[ -f "$HOME/.ssh/id_ed25519" ]]; then
  cp "$HOME/.ssh/id_ed25519" "$KEY_PATH"
else
  echo "No AUR SSH key found. Set AUR_SSH_PRIVATE_KEY_B64 or AUR_SSH_PRIVATE_KEY." >&2
  exit 1
fi

chmod 600 "$KEY_PATH"

if ! is_raw_ssh_key "$KEY_PATH"; then
  echo "AUR SSH key is not a valid OpenSSH private key after setup." >&2
  echo "Use either:" >&2
  echo "  - AUR_SSH_PRIVATE_KEY as File with raw key (BEGIN ... PRIVATE KEY)" >&2
  echo "  - AUR_SSH_PRIVATE_KEY_B64 as Variable with one-line base64 of that key" >&2
  exit 1
fi

ssh-keyscan aur.archlinux.org >> "$HOME/.ssh/known_hosts" 2>/dev/null || true
