#!/bin/bash
# Setup - Apply configuration to system
# Must run with sudo/as root
#
# Usage:
#   sudo ./setup.sh
#
# Prerequisites:
#   - Run ./configure.sh first (as appuser)
#
# This script:
#   - Installs system packages (docker, nginx, certbot)
#   - Applies generated nginx config to /etc/nginx/
#   - Manages nginx service

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
GEN_DIR="$SCRIPT_DIR/.generated"

echo "=== Core Room Setup (System Configuration) ==="
echo ""

# Must run as root
if [ "$EUID" -ne 0 ]; then
    echo "ERROR: This script must be run with sudo"
    echo "Usage: sudo ./setup.sh"
    exit 1
fi

# Get the actual user who ran sudo
if [ -z "$SUDO_USER" ]; then
    echo "ERROR: SUDO_USER not set"
    echo "Run with: sudo ./setup.sh (not as root directly)"
    exit 1
fi

ACTUAL_USER="$SUDO_USER"
ACTUAL_HOME=$(eval echo ~$ACTUAL_USER)

echo "Running as: root (via sudo)"
echo "Actual user: $ACTUAL_USER"
echo "User home: $ACTUAL_HOME"
echo ""

# Check that configure was run first
if [ ! -d "$GEN_DIR" ] || [ ! -f "$GEN_DIR/core_room.nginx.conf" ]; then
    echo "ERROR: Configuration files not found"
    echo ""
    echo "Run ./configure.sh first (as $ACTUAL_USER):"
    echo "  su - $ACTUAL_USER"
    echo "  cd $(dirname $SCRIPT_DIR)"
    echo "  ./server/configure.sh"
    exit 1
fi

echo "✓ Found generated configuration files"
echo ""

# =============================================================================
# 1. Install System Dependencies
# =============================================================================
echo "Step 1: Installing system dependencies..."
echo ""

# Docker
if ! command -v docker &> /dev/null; then
    echo "  Installing Docker..."
    curl -fsSL https://get.docker.com -o /tmp/get-docker.sh
    sh /tmp/get-docker.sh
    rm /tmp/get-docker.sh
    echo "  ✓ Docker installed"
else
    echo "  ✓ Docker already installed"
fi

# Add user to docker group
if ! groups "$ACTUAL_USER" | grep -q docker; then
    echo "  Adding $ACTUAL_USER to docker group..."
    usermod -aG docker "$ACTUAL_USER"
    echo "  ✓ $ACTUAL_USER added to docker group"
    echo "    (User must log out and back in for this to take effect)"
else
    echo "  ✓ $ACTUAL_USER already in docker group"
fi

# Docker Compose
if ! docker compose version &> /dev/null; then
    echo "  Installing Docker Compose plugin..."
    apt-get update
    apt-get install -y docker-compose-plugin
    echo "  ✓ Docker Compose installed"
else
    echo "  ✓ Docker Compose already installed"
fi

# Nginx
if ! command -v nginx &> /dev/null; then
    echo "  Installing Nginx..."
    apt-get update
    apt-get install -y nginx
    echo "  ✓ Nginx installed"
else
    echo "  ✓ Nginx already installed"
fi

# Certbot
if ! command -v certbot &> /dev/null; then
    echo "  Installing Certbot..."
    apt-get update
    apt-get install -y certbot python3-certbot-nginx
    echo "  ✓ Certbot installed"
else
    echo "  ✓ Certbot already installed"
fi

# =============================================================================
# 2. Install Nginx Configuration
# =============================================================================
echo ""
echo "Step 2: Installing nginx configuration..."

NGINX_AVAILABLE="/etc/nginx/sites-available/core_room.conf"
NGINX_ENABLED="/etc/nginx/sites-enabled/core_room.conf"
SOURCE_CONFIG="$GEN_DIR/core_room.nginx.conf"

# Copy generated config
cp "$SOURCE_CONFIG" "$NGINX_AVAILABLE"
echo "  ✓ Copied to: $NGINX_AVAILABLE"

# Enable site
ln -sf "$NGINX_AVAILABLE" "$NGINX_ENABLED"
echo "  ✓ Enabled site: $NGINX_ENABLED"

# Remove default site if exists
if [ -f "/etc/nginx/sites-enabled/default" ]; then
    rm "/etc/nginx/sites-enabled/default"
    echo "  ✓ Removed default site"
fi

# Test nginx config
echo "  Testing nginx configuration..."
if nginx -t; then
    echo "  ✓ Nginx configuration valid"
else
    echo "  ERROR: Nginx configuration test failed"
    exit 1
fi

# =============================================================================
# 3. Manage Nginx Service
# =============================================================================
echo ""
echo "Step 3: Managing nginx service..."

if systemctl is-active --quiet nginx; then
    echo "  Reloading nginx..."
    systemctl reload nginx
    echo "  ✓ Nginx reloaded"
else
    echo "  Starting nginx..."
    systemctl start nginx
    systemctl enable nginx
    echo "  ✓ Nginx started and enabled"
fi

# =============================================================================
# 4. SSL Certificate Information
# =============================================================================
echo ""
echo "Step 4: SSL certificates..."

SSL_CERTS=(
    "/etc/letsencrypt/live/room.mcrn.ar"
    "/etc/letsencrypt/live/mcrn.ar"
)

ALL_EXIST=true
for cert_dir in "${SSL_CERTS[@]}"; do
    if [ -d "$cert_dir" ]; then
        echo "  ✓ Certificate exists: $(basename $cert_dir)"
    else
        echo "  ⚠️  Certificate missing: $(basename $cert_dir)"
        ALL_EXIST=false
    fi
done

if [ "$ALL_EXIST" = false ]; then
    echo ""
    echo "  To generate missing certificates:"
    echo "    certbot certonly --manual --preferred-challenges dns -d '*.room.mcrn.ar'"
    echo "    certbot certonly --manual --preferred-challenges dns -d '*.mcrn.ar'"
    echo ""
    echo "  After generating, reload nginx:"
    echo "    systemctl reload nginx"
fi

# =============================================================================
# Done
# =============================================================================
echo ""
echo "=== Setup Complete ==="
echo ""
echo "System configuration applied successfully."
echo ""
echo "Next steps:"
echo "  1. If $ACTUAL_USER was added to docker group, they must:"
echo "     - Log out and log back in"
echo "     - Or run: newgrp docker"
echo ""
echo "  2. Generate SSL certificates if missing (see above)"
echo ""
echo "  3. Deploy application:"
echo "     su - $ACTUAL_USER"
echo "     cd $ACTUAL_HOME/core_room/ctrl"
echo "     ./deploy.sh"
echo ""
