#!/bin/bash
# Generate SSH test keys for TUI SSH testing
# Usage: ./scripts/testing/gen-ssh-test-keys.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
KEYS_DIR="${REPO_ROOT}/deployments/test_keys"

echo "=== Generating SSH Test Keys for TUI Testing ==="

# Create directory
mkdir -p "${KEYS_DIR}"

# Check if keys already exist
if [[ -f "${KEYS_DIR}/test_key" && -f "${KEYS_DIR}/test_key.pub" ]]; then
    echo "SSH keys already exist at ${KEYS_DIR}"
    echo "To regenerate, delete them first: rm -rf ${KEYS_DIR}"
    exit 0
fi

# Generate ED25519 key pair (preferred for modern systems)
echo "Generating ED25519 key pair..."
ssh-keygen -t ed25519 -f "${KEYS_DIR}/test_key" -N "" -C "fetchml-tui-test@local"

# Also generate RSA key for broader compatibility
echo "Generating RSA key pair for compatibility..."
ssh-keygen -t rsa -b 4096 -f "${KEYS_DIR}/test_key_rsa" -N "" -C "fetchml-tui-test-rsa@local"

# Set permissions
chmod 700 "${KEYS_DIR}"
chmod 600 "${KEYS_DIR}"/*
chmod 644 "${KEYS_DIR}"/*.pub

echo ""
echo "=== SSH Test Keys Generated ==="
echo "Location: ${KEYS_DIR}"
echo ""
echo "Files:"
ls -la "${KEYS_DIR}"
echo ""
echo "Public key (for SSH server):"
cat "${KEYS_DIR}/test_key.pub"
echo ""
echo "Usage:"
echo "  - Mount ${KEYS_DIR} to /tmp in SSH container"
echo "  - Container will use test_key.pub for authorized_keys"
echo "  - Tests will use test_key (private) for client connections"
