#!/bin/bash

# Droplet Setup Script for agents.jeffemmett.com
# Run this script on your DigitalOcean droplet as root

set -e

echo "🚀 Setting up agents.jeffemmett.com deployment environment..."

# Update system
echo "📦 Updating system packages..."
apt-get update
apt-get upgrade -y

# Install required packages
echo "📦 Installing required packages..."
apt-get install -y nginx python3 python3-pip nodejs npm git certbot python3-certbot-nginx curl

# Verify Node.js version (need v20+)
echo "📦 Installing Node.js 20..."
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs

# Create deployment directory
echo "📁 Creating deployment directory..."
mkdir -p /var/www/agents.jeffemmett.com
cd /var/www/agents.jeffemmett.com

# Clone repository (or pull if already exists)
if [ -d ".git" ]; then
    echo "📥 Pulling latest code..."
    git fetch origin main
    git reset --hard origin/main
else
    echo "📥 Cloning repository..."
    git clone https://github.com/Jeff-Emmett/infinite-agents.git .
    git checkout main
fi

# Install dependencies
echo "📦 Installing Node.js dependencies..."
npm ci

# Generate dashboard
echo "🎨 Generating dashboard..."
python3 generate_index.py

# Set proper permissions
echo "🔒 Setting permissions..."
chown -R www-data:www-data /var/www/agents.jeffemmett.com
chmod -R 755 /var/www/agents.jeffemmett.com

# Configure nginx
echo "🌐 Configuring nginx..."
cp deployment/nginx-config.conf /etc/nginx/sites-available/agents.jeffemmett.com
ln -sf /etc/nginx/sites-available/agents.jeffemmett.com /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# Test nginx configuration
nginx -t

# Obtain SSL certificate (only if not already present)
if [ ! -f /etc/letsencrypt/live/agents.jeffemmett.com/fullchain.pem ]; then
    echo "🔐 Obtaining SSL certificate..."
    echo "NOTE: Make sure DNS is pointing to this droplet before running certbot!"
    read -p "Press Enter to continue with certbot, or Ctrl+C to cancel..."
    certbot --nginx -d agents.jeffemmett.com --non-interactive --agree-tos --email admin@jeffemmett.com
else
    echo "✅ SSL certificate already exists"
fi

# Reload nginx
echo "🔄 Reloading nginx..."
systemctl reload nginx

# Enable nginx on boot
systemctl enable nginx

# Setup auto-renewal for SSL
echo "🔐 Setting up SSL auto-renewal..."
systemctl enable certbot.timer
systemctl start certbot.timer

echo ""
echo "✅ Setup complete!"
echo ""
echo "📋 Next steps:"
echo "1. Verify site is accessible at https://agents.jeffemmett.com"
echo "2. Add GitHub secrets for automated deployments:"
echo "   - DROPLET_HOST: 143.198.39.165"
echo "   - DROPLET_USER: root"
echo "   - DROPLET_SSH_KEY: (your private SSH key)"
echo ""
echo "3. Test deployment by pushing to main branch"
echo ""
