#!/bin/bash
# Server Cleanup - Run on AWS to prepare for fresh deployment
# This script safely cleans up old deployments
#
# Usage: ssh server 'cd ~/core_room/ctrl/server && ./cleanup.sh'

set -e

echo "=== SERVER CLEANUP ==="
echo ""
echo "⚠️  This will:"
echo "   - Stop all Docker containers"
echo "   - Remove old nginx configs"
echo "   - Keep data volumes and SSL certs"
echo "   - Keep .env files"
echo ""
read -p "Continue? (y/N) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Aborted."
    exit 1
fi

# =============================================================================
# 1. Stop Docker Containers
# =============================================================================
echo ""
echo "Step 1: Stopping Docker containers..."

# Stop containers if Docker is available
if command -v docker &> /dev/null; then
    # Stop all core_room/amar/soleprint containers
    CONTAINERS=$(docker ps -q --filter "name=core_room" --filter "name=amar" --filter "name=soleprint" 2>/dev/null || true)

    if [ -n "$CONTAINERS" ]; then
        echo "  Stopping containers..."
        docker stop $CONTAINERS 2>/dev/null || true
        echo "  ✓ Containers stopped"
    else
        echo "  ✓ No running containers to stop"
    fi
else
    echo "  ⓘ Docker not installed, skipping..."
fi

# =============================================================================
# 2. Stop Systemd Services
# =============================================================================
echo ""
echo "Step 2: Stopping systemd services..."

SERVICES=$(systemctl list-units --type=service --all --no-pager 2>/dev/null | grep -E "soleprint|artery|album|ward" | awk '{print $1}' || true)

if [ -n "$SERVICES" ]; then
    echo "  Found services: $SERVICES"
    for service in $SERVICES; do
        echo "  Stopping $service..."
        sudo systemctl stop "$service" 2>/dev/null || true
        sudo systemctl disable "$service" 2>/dev/null || true
    done
    echo "  ✓ Services stopped and disabled"
else
    echo "  ✓ No systemd services found"
fi

# =============================================================================
# 3. Clean Up Nginx Configs
# =============================================================================
echo ""
echo "Step 3: Cleaning up old nginx configs..."

if [ -d /etc/nginx/sites-enabled ]; then
    # Remove old individual configs
    OLD_CONFIGS=(
        "amar.room.mcrn.ar"
        "amar.room.mcrn.ar.conf"
        "api.amar.room.mcrn.ar"
        "api.amar.room.mcrn.ar.conf"
        "soleprint.mcrn.ar"
        "soleprint.mcrn.ar.conf"
        "artery.mcrn.ar"
        "artery.mcrn.ar.conf"
        "album.mcrn.ar"
        "album.mcrn.ar.conf"
        "ward.mcrn.ar"
        "ward.mcrn.ar.conf"
    )

    for config in "${OLD_CONFIGS[@]}"; do
        if [ -L "/etc/nginx/sites-enabled/$config" ] || [ -f "/etc/nginx/sites-enabled/$config" ]; then
            echo "  Removing /etc/nginx/sites-enabled/$config"
            sudo rm -f "/etc/nginx/sites-enabled/$config"
        fi
        if [ -f "/etc/nginx/sites-available/$config" ]; then
            echo "  Removing /etc/nginx/sites-available/$config"
            sudo rm -f "/etc/nginx/sites-available/$config"
        fi
    done

    echo "  ✓ Old nginx configs removed"

    # Test nginx config
    if command -v nginx &> /dev/null; then
        if sudo nginx -t 2>/dev/null; then
            echo "  Reloading nginx..."
            sudo systemctl reload nginx 2>/dev/null || true
        fi
    fi
else
    echo "  ⓘ Nginx not configured, skipping..."
fi

# =============================================================================
# 4. Verify What's Kept
# =============================================================================
echo ""
echo "Step 4: Verifying preserved data..."

# Check Docker volumes
if command -v docker &> /dev/null; then
    VOLUMES=$(docker volume ls -q | grep -E "core_room|amar|soleprint" 2>/dev/null || true)
    if [ -n "$VOLUMES" ]; then
        echo "  ✓ Docker volumes preserved:"
        docker volume ls | grep -E "core_room|amar|soleprint|DRIVER" || true
    fi
fi

# Check .env files
echo ""
echo "  .env files preserved:"
for envfile in ~/core_room/amar/.env ~/core_room/soleprint/.env ~/soleprint/.env; do
    [ -f "$envfile" ] && echo "    ✓ $envfile" || true
done

# Check SSL certs
echo ""
echo "  SSL certificates preserved:"
[ -d /etc/letsencrypt/live/room.mcrn.ar ] && echo "    ✓ *.room.mcrn.ar" || echo "    ✗ *.room.mcrn.ar (missing)"
[ -d /etc/letsencrypt/live/mcrn.ar ] && echo "    ✓ *.mcrn.ar" || echo "    ✗ *.mcrn.ar (missing)"

# =============================================================================
# Done
# =============================================================================
echo ""
echo "=== Cleanup Complete ==="
echo ""
echo "Next steps:"
echo "  1. Deploy from local:"
echo "       ./ctrl/deploy.sh"
echo ""
echo "  2. Run server setup:"
echo "       cd ~/core_room/ctrl/server && ./setup.sh"
echo ""
echo "  3. Build and start:"
echo "       cd ~/core_room/ctrl && ./build.sh && ./start.sh -d"
echo ""
