#!/usr/bin/env bash
# Write ~/.ssh/id_ed25519 for AUR pushes from CI or local scripts.
#
# Supported 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)
#
# Always normalizes CRLF → LF (Windows pastes into GitLab often break OpenSSH otherwise).
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
}

normalize_key_file() {
  local tmp
  tmp="$(mktemp)"
  tr -d '\r' < "$KEY_PATH" > "$tmp"
  if [[ -s "$tmp" ]] && [[ "$(tail -c1 "$tmp" | wc -l)" -eq 0 ]]; then
    printf '\n' >> "$tmp"
  fi
  mv "$tmp" "$KEY_PATH"
  chmod 600 "$KEY_PATH"
}

decode_b64_to_key() {
  local src="$1"
  if [[ -f "$src" ]]; then
    tr -d '\r\n[:space:]' < "$src" | base64 -d > "$KEY_PATH"
  else
    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
    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

normalize_key_file

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
  echo "Tip: generate base64 from a LF-normalized key (see docs/CI.md)." >&2
  exit 1
fi

if ! ssh-keygen -y -f "$KEY_PATH" >/dev/null 2>&1; then
  echo "AUR SSH key failed ssh-keygen validation (often CRLF or truncated paste)." >&2
  exit 1
fi

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