#!/bin/bash
# Generate SSH deploy key for a GitHub repository
#
# Usage: ./generate-deploy-key.sh <project-name>
# Example: ./generate-deploy-key.sh pantheon
#
# This generates:
#   - <project>-deploy-key (private key)
#   - <project>-deploy-key.pub (public key - add to GitHub)
#   - <project>-deploy-key.b64 (base64 encoded for K8s secret)

set -e

if [ -z "$1" ]; then
  echo "Usage: $0 <project-name>"
  echo "Example: $0 pantheon"
  exit 1
fi

PROJECT="$1"
KEY_FILE="${PROJECT}-deploy-key"

echo "Generating deploy key for project: $PROJECT"
echo ""

# Check if key already exists
if [ -f "$KEY_FILE" ]; then
  echo "WARNING: Key file $KEY_FILE already exists!"
  read -p "Overwrite? (y/N) " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Aborted."
    exit 1
  fi
fi

# Generate ED25519 key (no passphrase for automated use)
ssh-keygen -t ed25519 -f "$KEY_FILE" -N "" -C "rdev-${PROJECT}@orchard9.ai"

# Create base64 encoded version for K8s secret
cat "$KEY_FILE" | base64 > "${KEY_FILE}.b64"

echo ""
echo "=== Generated Files ==="
echo ""
echo "Private key: $KEY_FILE"
echo "Public key:  ${KEY_FILE}.pub"
echo "Base64:      ${KEY_FILE}.b64"
echo ""
echo "=== Next Steps ==="
echo ""
echo "1. Add the PUBLIC key to GitHub:"
echo "   - Go to: https://github.com/orchard9/${PROJECT}/settings/keys"
echo "   - Click 'Add deploy key'"
echo "   - Title: rdev-${PROJECT}"
echo "   - Key: (paste contents of ${KEY_FILE}.pub)"
echo "   - Check 'Allow write access' if you need push capability"
echo ""
echo "   Public key to copy:"
echo "   ---"
cat "${KEY_FILE}.pub"
echo "   ---"
echo ""
echo "2. Update the Kubernetes secret:"
echo "   - Edit deployments/k8s/base/secrets.yaml"
echo "   - Replace REPLACE_WITH_BASE64_ENCODED_PRIVATE_KEY for ${PROJECT}"
echo "   - With contents of: ${KEY_FILE}.b64"
echo ""
echo "   Base64 encoded private key:"
echo "   ---"
cat "${KEY_FILE}.b64"
echo "   ---"
echo ""
echo "3. Apply the secret:"
echo "   export KUBECONFIG=~/.kube/orchard9-k3sf.yaml"
echo "   kubectl apply -f deployments/k8s/base/secrets.yaml"
echo ""
echo "4. IMPORTANT: Keep the private key files secure!"
echo "   - Do NOT commit them to git"
echo "   - Store them securely or delete after updating K8s secret"
echo ""
