#!/bin/bash
# VIP Coordinator Droplet Setup Script
# Run this on a fresh Ubuntu 24.04 droplet

set -e

echo "=== VIP Coordinator Droplet Setup ==="
echo ""

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

# Install Docker
echo ">>> Installing Docker..."
apt-get install -y ca-certificates curl gnupg
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg

echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null

apt-get update
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# Enable Docker to start on boot
systemctl enable docker
systemctl start docker

echo ">>> Docker installed: $(docker --version)"

# Install Nginx and Certbot for SSL
echo ">>> Installing Nginx and Certbot..."
apt-get install -y nginx certbot python3-certbot-nginx

# Create app directory
echo ">>> Setting up application directory..."
mkdir -p /opt/vip-coordinator
cd /opt/vip-coordinator

# Create docker-compose.yml
echo ">>> Creating docker-compose.yml..."
cat > docker-compose.yml << 'COMPOSE'
services:
  # PostgreSQL Database
  postgres:
    image: postgres:15-alpine
    container_name: vip-postgres
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-changeme}
      POSTGRES_DB: vip_coordinator
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5
    restart: unless-stopped
    networks:
      - vip-network

  # Redis (for caching/sessions)
  redis:
    image: redis:7-alpine
    container_name: vip-redis
    volumes:
      - redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5
    restart: unless-stopped
    networks:
      - vip-network

  # Signal CLI REST API for messaging
  signal-api:
    image: bbernhard/signal-cli-rest-api:latest
    container_name: vip-signal
    environment:
      - MODE=native
    volumes:
      - signal_data:/home/.local/share/signal-cli
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/v1/about"]
      interval: 30s
      timeout: 10s
      retries: 3
    restart: unless-stopped
    networks:
      - vip-network

  # Backend API
  backend:
    image: t72chevy/vip-coordinator-backend:latest
    container_name: vip-backend
    environment:
      NODE_ENV: production
      PORT: 3000
      DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD:-changeme}@postgres:5432/vip_coordinator
      REDIS_URL: redis://redis:6379
      SIGNAL_API_URL: http://signal-api:8080
      AUTH0_DOMAIN: ${AUTH0_DOMAIN}
      AUTH0_AUDIENCE: ${AUTH0_AUDIENCE}
      AUTH0_ISSUER: ${AUTH0_ISSUER}
      FRONTEND_URL: https://${DOMAIN_NAME}
      ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY}
    ports:
      - "127.0.0.1:3000:3000"
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/v1/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s
    restart: unless-stopped
    networks:
      - vip-network

  # Frontend
  frontend:
    image: t72chevy/vip-coordinator-frontend:latest
    container_name: vip-frontend
    ports:
      - "127.0.0.1:5173:80"
    depends_on:
      - backend
    restart: unless-stopped
    networks:
      - vip-network

volumes:
  postgres_data:
    name: vip_postgres_data
  redis_data:
    name: vip_redis_data
  signal_data:
    name: vip_signal_data

networks:
  vip-network:
    driver: bridge
COMPOSE

# Create .env file template
echo ">>> Creating .env file..."
cat > .env << 'ENVFILE'
# Database
POSTGRES_PASSWORD=CHANGE_THIS_TO_SECURE_PASSWORD

# Domain
DOMAIN_NAME=vip.madeamess.online

# Auth0
AUTH0_DOMAIN=dev-s855cy3bvjjbkljt.us.auth0.com
AUTH0_AUDIENCE=https://vip-coordinator-api
AUTH0_ISSUER=https://dev-s855cy3bvjjbkljt.us.auth0.com/

# Anthropic API (for AI Copilot)
ANTHROPIC_API_KEY=PASTE_YOUR_API_KEY_HERE
ENVFILE

echo ">>> IMPORTANT: Edit /opt/vip-coordinator/.env with your actual values!"
echo ""

# Configure Nginx as reverse proxy
echo ">>> Configuring Nginx..."
cat > /etc/nginx/sites-available/vip-coordinator << 'NGINX'
server {
    listen 80;
    server_name vip.madeamess.online;

    # Redirect HTTP to HTTPS (will be enabled after certbot)
    # location / {
    #     return 301 https://$host$request_uri;
    # }

    # API proxy - forward /api requests to backend
    location /api/ {
        proxy_pass http://127.0.0.1:3000/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }

    # Frontend
    location / {
        proxy_pass http://127.0.0.1:5173;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
}
NGINX

# Enable the site
ln -sf /etc/nginx/sites-available/vip-coordinator /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# Test and reload nginx
nginx -t && systemctl reload nginx

# Configure firewall
echo ">>> Configuring UFW firewall..."
ufw allow OpenSSH
ufw allow 'Nginx Full'
ufw --force enable

echo ""
echo "=== Setup Complete ==="
echo ""
echo "Next steps:"
echo "1. Edit /opt/vip-coordinator/.env with your actual values:"
echo "   - Set POSTGRES_PASSWORD to a secure password"
echo "   - Set ANTHROPIC_API_KEY to your API key"
echo ""
echo "2. Start the stack:"
echo "   cd /opt/vip-coordinator"
echo "   docker compose pull"
echo "   docker compose up -d"
echo ""
echo "3. Wait for backend to start, then run database migration:"
echo "   docker exec vip-backend npx prisma migrate deploy"
echo ""
echo "4. Get SSL certificate:"
echo "   certbot --nginx -d vip.madeamess.online"
echo ""
echo "5. Update Auth0 callback URLs to:"
echo "   https://vip.madeamess.online/callback"
echo ""
echo "Droplet IP: $(curl -s ifconfig.me)"
echo ""
