#!/usr/bin/env bash
# ============================================================================
# Update Age Keys from SSH Public Keys
# ============================================================================
# This script converts SSH public keys to age format for use with ragenix.
# Run this after adding new SSH .pub files to create corresponding .age.pub files.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "Converting SSH public keys to age format..."

# Find all .pub files that are SSH keys (not already .age.pub)
find . -name "*.pub" -not -name "*.age.pub" -type f | while read -r pubkey; do
    # Check if it's an SSH key
    if grep -q "^ssh-" "$pubkey" 2>/dev/null || grep -q "^ecdsa-" "$pubkey" 2>/dev/null; then
        age_key=$(nix shell nixpkgs#ssh-to-age -c ssh-to-age < "$pubkey" 2>/dev/null || true)
        
        if [ -n "$age_key" ]; then
            # Create .age.pub file with the age key
            age_file="${pubkey%.pub}.age.pub"
            echo "$age_key" > "$age_file"
            echo "✓ Converted: $pubkey -> $age_file"
        else
            echo "⚠ Skipped: $pubkey (conversion failed)"
        fi
    fi
done

echo ""
echo "Done! Age public keys have been generated."
echo "You can now use ragenix to manage secrets:"
echo "  ragenix -e secrets/global/my-secret.age"
echo "  ragenix -r  # Re-key all secrets with updated keys"
