#!/bin/bash

# ThrillWiki Template VM SSH Key Setup Helper
# This script generates the SSH key needed for template VM access

set -e

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}ThrillWiki Template VM SSH Key Setup${NC}"
echo "[AWS-SECRET-REMOVED]"
echo

SSH_KEY_PATH="$HOME/.ssh/thrillwiki_vm"

# Generate SSH key if it doesn't exist
if [ ! -f "$SSH_KEY_PATH" ]; then
    echo -e "${YELLOW}Generating new SSH key for ThrillWiki template VM...${NC}"
    ssh-keygen -t rsa -b 4096 -f "$SSH_KEY_PATH" -N "" -C "thrillwiki-template-vm-access"
    echo -e "${GREEN}✅ SSH key generated: $SSH_KEY_PATH${NC}"
    echo
else
    echo -e "${GREEN}✅ SSH key already exists: $SSH_KEY_PATH${NC}"
    echo
fi

# Display the public key
echo -e "${YELLOW}📋 Your SSH Public Key:${NC}"
echo "Copy this ENTIRE line and add it to your template VM:"
echo
echo -e "${GREEN}$(cat "$SSH_KEY_PATH.pub")${NC}"
echo

# Instructions
echo -e "${BLUE}📝 Template VM Setup Instructions:${NC}"
echo "1. SSH into your template VM (thrillwiki-template-ubuntu)"
echo "2. Switch to the thrillwiki user:"
echo "   sudo su - thrillwiki"
echo "3. Create .ssh directory and set permissions:"
echo "   mkdir -p ~/.ssh && chmod 700 ~/.ssh"
echo "4. Add the public key above to ***REMOVED***:"
echo "   echo 'YOUR_PUBLIC_KEY_HERE' >> ~/.ssh/***REMOVED***"
echo "   chmod 600 ~/.ssh/***REMOVED***"
echo "5. Test SSH access:"
echo "   ssh -i ~/.ssh/thrillwiki_vm thrillwiki@YOUR_TEMPLATE_VM_IP"
echo

# SSH config helper
SSH_CONFIG="$HOME/.ssh/config"
echo -e "${BLUE}🔧 SSH Config Setup:${NC}"
if ! grep -q "thrillwiki-vm" "$SSH_CONFIG" 2>/dev/null; then
    echo "Adding SSH config entry..."
    cat >> "$SSH_CONFIG" << EOF

# ThrillWiki Template VM
Host thrillwiki-vm
    HostName %h
    User thrillwiki
    IdentityFile $SSH_KEY_PATH
    StrictHostKeyChecking no
    UserKnownHostsFile /dev/null
EOF
    echo -e "${GREEN}✅ SSH config updated${NC}"
else
    echo -e "${GREEN}✅ SSH config already contains thrillwiki-vm entry${NC}"
fi

echo
echo -e "${GREEN}🎉 SSH key setup complete!${NC}"
echo "Next: Set up your template VM using TEMPLATE_VM_SETUP.md"
echo "Then run: ./setup-template-automation.sh"
