#!/usr/bin/env bash
# One-time setup: Ubuntu One login + GPG signing key for custom UC26 dev models.
set -euo pipefail

UC_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${UC_ROOT}/config/dev-image.env"
EXAMPLE="${UC_ROOT}/config/dev-image.env.example"
KEY_NAME="${SIGN_KEY_NAME:-salmanoff-dev}"
SSH_DIR="${UC_ROOT}/config/ssh"
SSH_PRIV="${SSH_DIR}/smo-dev"
SSH_PUB="${SSH_DIR}/smo-dev.pub"

usage() {
    cat <<'EOF'
Usage: setup-dev-signing.sh [OPTIONS]

Prepare signing credentials for dangerous-grade salmanoff-dev-amd64 images.

This script:
  1. Ensures an SSH keypair exists for the seeded system user (smo).
  2. Guides snapcraft login + create-key + register-key (interactive).
  3. Writes config/dev-image.env with your Snap Store account id.

Options:
  --key-name NAME   Signing key name (default: salmanoff-dev)
  -h, --help        Show this help

After setup, run:
  scripts/sign-dev-assertions.sh
  scripts/build-dev-image.sh
EOF
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        --key-name) KEY_NAME="$2"; shift 2 ;;
        -h|--help) usage; exit 0 ;;
        *) echo "Unknown option: $1" >&2; usage >&2; exit 1 ;;
    esac
done

mkdir -p "$SSH_DIR"

if [[ ! -f "$SSH_PUB" ]]; then
    echo "Generating SSH keypair for system user: $SSH_PRIV"
    ssh-keygen -t ed25519 -N "" -f "$SSH_PRIV" -C "smo-dev@salmanoff"
fi

if ! command -v snapcraft >/dev/null 2>&1; then
    echo "snapcraft not found. Install with: sudo snap install snapcraft --classic" >&2
    exit 1
fi

echo ""
echo "=== Step 1: log in to the Snap Store (Ubuntu One) ==="
echo "Run:  snapcraft login"
echo ""
if ! snapcraft whoami >/dev/null 2>&1; then
    echo "Not logged in yet. Complete 'snapcraft login' in this terminal, then re-run this script." >&2
    exit 1
fi

ACCOUNT_ID="$(snapcraft whoami 2>/dev/null | awk '/^id:/ {print $2}')"
if [[ -z "$ACCOUNT_ID" ]]; then
    echo "Could not read account id from 'snapcraft whoami'" >&2
    exit 1
fi
echo "Account id: $ACCOUNT_ID"

echo ""
echo "=== Step 2: create and register a signing key ==="
if ! snap keys 2>/dev/null | awk 'NR>1 {print $1}' | grep -qx "$KEY_NAME"; then
    echo "No local key named '$KEY_NAME'."
    echo "Run interactively (you will choose a passphrase):"
    echo "  snapcraft create-key $KEY_NAME"
    echo "  snapcraft register-key $KEY_NAME"
    echo ""
    echo "Re-run this script after both commands succeed." >&2
    exit 1
fi

KEY_FP="$(snap keys 2>/dev/null | awk -v k="$KEY_NAME" '$1 == k {print $2}')"
if [[ -z "$KEY_FP" ]]; then
    echo "Could not read SHA3-384 fingerprint for key '$KEY_NAME'" >&2
    exit 1
fi

if ! snap known --remote account-key "public-key-sha3-384=${KEY_FP}" >/dev/null 2>&1; then
    echo "Key '$KEY_NAME' exists locally but is not registered in the store."
    echo "Run:  snapcraft register-key $KEY_NAME"
    echo "Then re-run this script." >&2
    exit 1
fi

echo "Signing key: $KEY_NAME ($KEY_FP)"

if [[ ! -f "$ENV_FILE" ]]; then
    cp "$EXAMPLE" "$ENV_FILE"
fi

tmp="$(mktemp)"
while IFS= read -r line || [[ -n "$line" ]]; do
    case "$line" in
        ACCOUNT_ID=*) echo "ACCOUNT_ID=${ACCOUNT_ID}" ;;
        SIGN_KEY_NAME=*) echo "SIGN_KEY_NAME=${KEY_NAME}" ;;
        SSH_PUBKEY_FILE=*) echo "SSH_PUBKEY_FILE=config/ssh/smo-dev.pub" ;;
        *) echo "$line" ;;
    esac
done < "$ENV_FILE" > "$tmp"
mv "$tmp" "$ENV_FILE"

echo ""
echo "Wrote $ENV_FILE"
echo ""
echo "Next:"
echo "  scripts/sign-dev-assertions.sh"
echo "  scripts/build-dev-image.sh"
echo ""
echo "SSH to the VM after first boot:"
echo "  ssh -i ${SSH_PRIV} smo@localhost -p 8022"
