#!/usr/bin/env bash
# LLMHosts.com VPS Bootstrap Script
# Deploy from scratch on any Ubuntu 22.04+ VPS.
#
# Usage:
#   curl -sSL https://raw.githubusercontent.com/LookNoHandsMom/LLMHosts.com/main/infrastructure/deploy.sh | bash
#   # OR
#   ./infrastructure/deploy.sh
#
# Prerequisites: Ubuntu 22.04+, root or sudo access, 2GB+ RAM, Docker not required (script installs it).

set -euo pipefail

REPO="https://github.com/LookNoHandsMom/LLMHosts.com.git"
INSTALL_DIR="/home/dev/projects/LLMHosts.com"
DOMAIN="${LLMHOSTS_DOMAIN:-localhost}"

echo "=== LLMHosts.com VPS Bootstrap ==="
echo "Domain: $DOMAIN"
echo ""

# 1. System dependencies
echo "[1/6] Installing system dependencies..."
sudo apt-get update -qq
sudo apt-get install -y -qq git curl ca-certificates gnupg lsb-release

# 2. Docker (if not installed)
if ! command -v docker &>/dev/null; then
    echo "[2/6] Installing Docker..."
    curl -fsSL https://get.docker.com | sh
    sudo usermod -aG docker "${USER:-dev}"
    sudo systemctl enable docker
    sudo systemctl start docker
else
    echo "[2/6] Docker already installed."
fi

# 3. Docker Compose plugin (if not installed)
if ! docker compose version &>/dev/null; then
    echo "[3/6] Installing Docker Compose plugin..."
    sudo apt-get install -y -qq docker-compose-plugin
else
    echo "[3/6] Docker Compose already installed."
fi

# 4. Clone repository
if [ -d "$INSTALL_DIR" ]; then
    echo "[4/6] Repository exists, pulling latest..."
    cd "$INSTALL_DIR" && git pull origin main
else
    echo "[4/6] Cloning repository..."
    sudo mkdir -p "$(dirname "$INSTALL_DIR")"
    sudo chown -R "${USER:-dev}:${USER:-dev}" "$(dirname "$INSTALL_DIR")"
    git clone "$REPO" "$INSTALL_DIR"
    cd "$INSTALL_DIR"
fi

# 5. Environment setup
if [ ! -f "$INSTALL_DIR/.env" ]; then
    echo "[5/6] Creating .env from example..."
    cp "$INSTALL_DIR/.env.example" "$INSTALL_DIR/.env"
    echo ""
    echo "  IMPORTANT: Edit $INSTALL_DIR/.env with your secrets before starting."
    echo "  Required: AUTH_SECRET, DATABASE_URL, NEXTAUTH_URL"
    echo ""
else
    echo "[5/6] .env already exists."
fi

# 6. Build and start
echo "[6/6] Building and starting services..."
cd "$INSTALL_DIR"
docker compose -f docker-compose.prod.yml build
docker compose -f docker-compose.prod.yml up -d

echo ""
echo "=== LLMHosts.com deployed! ==="
echo "Backend:  http://$DOMAIN:4000/health"
echo "Frontend: http://$DOMAIN:3000"
echo ""
echo "Next steps:"
echo "  1. Edit .env with your secrets"
echo "  2. For external proxy (Traefik/nginx), use:"
echo "     docker compose -f docker-compose.prod.yml -f docker-compose.external-proxy.yml up -d"
echo "  3. For Hive Mode (Phase 3):"
echo "     cd infrastructure/headscale && docker compose up -d"
echo ""
