| 1 | #!/usr/bin/env bash |
| 2 | # Write ~/.ssh/id_ed25519 for AUR pushes from CI or local scripts. |
| 3 | # |
| 4 | # Supported GitLab CI variables (pick one): |
| 5 | # AUR_SSH_PRIVATE_KEY_B64 — base64 of the private key (Variable type, one line; Masked OK) |
| 6 | # or File type whose contents are that base64 string |
| 7 | # AUR_SSH_PRIVATE_KEY — raw OpenSSH private key (File type preferred), or raw key text |
| 8 | # File contents may also be base64 (auto-detected) |
| 9 | set -euo pipefail |
| 10 | |
| 11 | KEY_PATH="${1:-$HOME/.ssh/id_ed25519}" |
| 12 | |
| 13 | install -d -m 700 "$(dirname "$KEY_PATH")" |
| 14 | |
| 15 | is_raw_ssh_key() { |
| 16 | grep -qE 'BEGIN (OPENSSH |RSA |EC )?PRIVATE KEY' "$1" 2>/dev/null |
| 17 | } |
| 18 | |
| 19 | decode_b64_to_key() { |
| 20 | local src="$1" |
| 21 | if [[ -f "$src" ]]; then |
| 22 | # GitLab File variable: env value is a path to a temp file |
| 23 | tr -d '\r\n[:space:]' < "$src" | base64 -d > "$KEY_PATH" |
| 24 | else |
| 25 | # Variable type: env value is the base64 string itself |
| 26 | printf '%s' "$src" | tr -d '\r\n[:space:]' | base64 -d > "$KEY_PATH" |
| 27 | fi |
| 28 | } |
| 29 | |
| 30 | if [[ -n "${AUR_SSH_PRIVATE_KEY_B64:-}" ]]; then |
| 31 | decode_b64_to_key "$AUR_SSH_PRIVATE_KEY_B64" |
| 32 | elif [[ -n "${AUR_SSH_PRIVATE_KEY:-}" && -f "${AUR_SSH_PRIVATE_KEY}" ]]; then |
| 33 | if is_raw_ssh_key "$AUR_SSH_PRIVATE_KEY"; then |
| 34 | cp "$AUR_SSH_PRIVATE_KEY" "$KEY_PATH" |
| 35 | else |
| 36 | # File variable mistakenly filled with base64 instead of raw PEM |
| 37 | decode_b64_to_key "$AUR_SSH_PRIVATE_KEY" |
| 38 | fi |
| 39 | elif [[ -n "${AUR_SSH_PRIVATE_KEY:-}" ]]; then |
| 40 | if printf '%s' "$AUR_SSH_PRIVATE_KEY" | grep -qE 'BEGIN (OPENSSH |RSA |EC )?PRIVATE KEY'; then |
| 41 | printf '%s\n' "$AUR_SSH_PRIVATE_KEY" > "$KEY_PATH" |
| 42 | else |
| 43 | decode_b64_to_key "$AUR_SSH_PRIVATE_KEY" |
| 44 | fi |
| 45 | elif [[ -f "$HOME/.ssh/id_ed25519" ]]; then |
| 46 | cp "$HOME/.ssh/id_ed25519" "$KEY_PATH" |
| 47 | else |
| 48 | echo "No AUR SSH key found. Set AUR_SSH_PRIVATE_KEY_B64 or AUR_SSH_PRIVATE_KEY." >&2 |
| 49 | exit 1 |
| 50 | fi |
| 51 | |
| 52 | chmod 600 "$KEY_PATH" |
| 53 | |
| 54 | if ! is_raw_ssh_key "$KEY_PATH"; then |
| 55 | echo "AUR SSH key is not a valid OpenSSH private key after setup." >&2 |
| 56 | echo "Use either:" >&2 |
| 57 | echo " - AUR_SSH_PRIVATE_KEY as File with raw key (BEGIN ... PRIVATE KEY)" >&2 |
| 58 | echo " - AUR_SSH_PRIVATE_KEY_B64 as Variable with one-line base64 of that key" >&2 |
| 59 | exit 1 |
| 60 | fi |
| 61 | |
| 62 | ssh-keyscan aur.archlinux.org >> "$HOME/.ssh/known_hosts" 2>/dev/null || true |