#!/bin/bash

echo "=== V2-Docker Deployment Verification Script ==="
echo

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check function
check() {
    if [ $1 -eq 0 ]; then
        echo -e "${GREEN}✓${NC} $2"
    else
        echo -e "${RED}✗${NC} $2"
        return 1
    fi
}

# Warning function
warn() {
    echo -e "${YELLOW}⚠${NC} $1"
}

echo "1. Checking Docker installation..."
docker --version > /dev/null 2>&1
check $? "Docker installed"

docker compose version > /dev/null 2>&1
check $? "Docker Compose installed"

echo
echo "2. Checking SSL certificates..."
if [ -f "v2_nginx/ssl/fullchain.pem" ]; then
    check 0 "fullchain.pem exists"
else
    check 1 "fullchain.pem missing - copy from /SSL/ or your certificate location"
fi

if [ -f "v2_nginx/ssl/privkey.pem" ]; then
    check 0 "privkey.pem exists"
else
    check 1 "privkey.pem missing - copy from /SSL/ or your certificate location"
fi

if [ -f "v2_nginx/ssl/dhparam.pem" ]; then
    check 0 "dhparam.pem exists"
else
    warn "dhparam.pem missing - will be generated (this takes a few minutes)"
fi

echo
echo "3. Checking configuration files..."
if grep -q "intelsight.de" v2_nginx/nginx.conf; then
    check 0 "nginx.conf has correct domain (intelsight.de)"
else
    check 1 "nginx.conf still has test domain"
fi

if grep -q "intelsight.de" v2/.env; then
    check 0 ".env has correct domain (intelsight.de)"
else
    check 1 ".env still has test domain"
fi

echo
echo "4. Checking Docker services..."
cd v2 2>/dev/null
if [ $? -eq 0 ]; then
    if docker compose ps 2>/dev/null | grep -q "running"; then
        check 0 "Docker services are running"
        docker compose ps
    else
        warn "Docker services not running yet"
    fi
    cd ..
else
    warn "v2 directory not found"
fi

echo
echo "5. Checking network connectivity..."
if command -v ss &> /dev/null; then
    if ss -tlnp 2>/dev/null | grep -q ":80"; then
        check 0 "Port 80 is listening"
    else
        warn "Port 80 not listening yet"
    fi
    
    if ss -tlnp 2>/dev/null | grep -q ":443"; then
        check 0 "Port 443 is listening"
    else
        warn "Port 443 not listening yet"
    fi
else
    warn "ss command not found, skipping port check"
fi

echo
echo "=== Quick Start Commands ==="
echo
echo "1. If SSL certificates are missing:"
echo "   cp /SSL/fullchain.pem v2_nginx/ssl/"
echo "   cp /SSL/privkey.pem v2_nginx/ssl/"
echo "   chmod 644 v2_nginx/ssl/fullchain.pem"
echo "   chmod 600 v2_nginx/ssl/privkey.pem"
echo
echo "2. Generate dhparam.pem if missing:"
echo "   openssl dhparam -out v2_nginx/ssl/dhparam.pem 2048"
echo
echo "3. Start Docker services:"
echo "   cd v2"
echo "   docker compose up -d"
echo
echo "4. Check logs:"
echo "   docker compose logs -f"
echo
echo "=== URLs after deployment ==="
echo "Admin Panel: https://admin-panel-undso.intelsight.de"
echo "API Server: https://api-software-undso.intelsight.de"
echo