#!/usr/bin/env bash
set -euo pipefail

# ─────────────────────────────────────────────────────────────────────────────
# Divisi Metrics — EC2 Deployment Script
#
# Usage:
#   1. Launch an EC2 instance (Amazon Linux 2023 or Ubuntu 22.04+)
#   2. SSH into the instance
#   3. Clone the repo or copy the project files
#   4. Copy .env.example to .env and fill in your values
#   5. Run: chmod +x deploy.sh && ./deploy.sh
#
# This script will:
#   - Install Docker and Docker Compose (if not present)
#   - Install and configure Nginx (if not present)
#   - Build and start the application
# ─────────────────────────────────────────────────────────────────────────────

echo "╔══════════════════════════════════════════╗"
echo "║   Divisi Metrics — EC2 Deployment        ║"
echo "╚══════════════════════════════════════════╝"
echo ""

# ── Detect OS ────────────────────────────────────────────────────────────────

if [ -f /etc/os-release ]; then
  . /etc/os-release
  OS_ID="$ID"
else
  echo "❌ Cannot detect OS. Supported: Amazon Linux 2023, Ubuntu 22.04+"
  exit 1
fi

echo "→ Detected OS: $OS_ID"

# ── Install Docker ───────────────────────────────────────────────────────────

if ! command -v docker &> /dev/null; then
  echo "→ Installing Docker..."
  if [[ "$OS_ID" == "amzn" ]]; then
    sudo dnf update -y
    sudo dnf install -y docker
    sudo systemctl start docker
    sudo systemctl enable docker
    sudo usermod -aG docker "$USER"
  elif [[ "$OS_ID" == "ubuntu" ]]; then
    sudo apt-get update -y
    sudo apt-get install -y ca-certificates curl gnupg
    sudo install -m 0755 -d /etc/apt/keyrings
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
    sudo 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 $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
    sudo apt-get update -y
    sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
    sudo systemctl start docker
    sudo systemctl enable docker
    sudo usermod -aG docker "$USER"
  else
    echo "❌ Unsupported OS for automatic Docker install. Install Docker manually."
    exit 1
  fi
  echo "✓ Docker installed"
else
  echo "✓ Docker already installed"
fi

# ── Install Docker Compose (standalone, if plugin not available) ─────────────

if ! docker compose version &> /dev/null; then
  if ! command -v docker-compose &> /dev/null; then
    echo "→ Installing Docker Compose..."
    COMPOSE_VERSION="v2.29.1"
    sudo curl -L "https://github.com/docker/compose/releases/download/${COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    sudo chmod +x /usr/local/bin/docker-compose
    echo "✓ Docker Compose installed"
  else
    echo "✓ Docker Compose (standalone) already installed"
  fi
else
  echo "✓ Docker Compose (plugin) already installed"
fi

# Helper: run docker compose regardless of plugin vs standalone
docker_compose() {
  if docker compose version &> /dev/null; then
    docker compose "$@"
  else
    docker-compose "$@"
  fi
}

# ── Install Nginx ────────────────────────────────────────────────────────────

if ! command -v nginx &> /dev/null; then
  echo "→ Installing Nginx..."
  if [[ "$OS_ID" == "amzn" ]]; then
    sudo dnf install -y nginx
  elif [[ "$OS_ID" == "ubuntu" ]]; then
    sudo apt-get install -y nginx
  fi
  sudo systemctl enable nginx
  echo "✓ Nginx installed"
else
  echo "✓ Nginx already installed"
fi

# ── Check .env file ──────────────────────────────────────────────────────────

if [ ! -f .env ]; then
  echo ""
  echo "⚠  No .env file found."
  echo "   Copy .env.example to .env and fill in your values:"
  echo "   cp .env.example .env"
  echo ""
  echo "   The app will still run without S3 credentials,"
  echo "   but logo uploads won't work."
  echo ""
fi

# ── Build and start the app ──────────────────────────────────────────────────

echo "→ Building Docker image..."
docker_compose build

echo "→ Starting application..."
docker_compose up -d

echo "→ Waiting for health check..."
sleep 5

if curl -sf http://localhost:3000 > /dev/null 2>&1; then
  echo "✓ Application is running on port 3000"
else
  echo "⚠  Application may still be starting. Check with: docker compose logs -f"
fi

# ── Configure Nginx ──────────────────────────────────────────────────────────

echo "→ Configuring Nginx..."

# Start with HTTP-only config (no SSL). User can add SSL later.
sudo tee /etc/nginx/conf.d/divisi-metrics.conf > /dev/null <<'NGINX'
upstream nextjs_app {
    server 127.0.0.1:3000;
}

server {
    listen 80;
    server_name _;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    # Gzip compression
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_min_length 256;

    # Proxy to Next.js
    location / {
        proxy_pass http://nextjs_app;
        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;
    }

    # Cache static assets aggressively
    location /_next/static {
        proxy_pass http://nextjs_app;
        add_header Cache-Control "public, max-age=31536000, immutable";
    }
}
NGINX

# Remove default site if it exists
sudo rm -f /etc/nginx/sites-enabled/default 2>/dev/null || true
# On Amazon Linux, remove the default server block in nginx.conf
if [[ "$OS_ID" == "amzn" ]]; then
  sudo sed -i '/^[[:space:]]*server {/,/^[[:space:]]*}/d' /etc/nginx/nginx.conf 2>/dev/null || true
fi

sudo nginx -t && sudo systemctl restart nginx
echo "✓ Nginx configured and running"

# ── Done ─────────────────────────────────────────────────────────────────────

PUBLIC_IP=$(curl -sf http://169.254.169.254/latest/meta-data/public-ipv4 2>/dev/null || echo "<your-ec2-public-ip>")

echo ""
echo "╔══════════════════════════════════════════╗"
echo "║   ✓ Deployment complete!                 ║"
echo "╚══════════════════════════════════════════╝"
echo ""
echo "  App URL:  http://${PUBLIC_IP}"
echo ""
echo "  Useful commands:"
echo "    docker compose logs -f        # View logs"
echo "    docker compose restart        # Restart app"
echo "    docker compose down           # Stop app"
echo "    docker compose up -d --build  # Rebuild & restart"
echo ""
echo "  To add HTTPS (recommended):"
echo "    1. Point a domain to ${PUBLIC_IP}"
echo "    2. sudo apt install certbot python3-certbot-nginx  # or dnf"
echo "    3. sudo certbot --nginx -d yourdomain.com"
echo ""
