#!/bin/bash
# ================================================================
# Nexus 6.0 — Uninstall Script
#
# Usage:
#   sudo bash uninstall.sh                          # interactive
#   sudo bash uninstall.sh --deploy-dir /opt/nexus   # specify deploy dir
#   sudo bash uninstall.sh --purge                   # also remove deploy dir
#
# Safe: stops services, removes configs. Database is NEVER deleted automatically.
# ================================================================

set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

info()  { echo -e "${GREEN}[INFO]${NC} $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*"; }

DEPLOY_DIR=""
PURGE=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --deploy-dir) DEPLOY_DIR="$2"; shift 2 ;;
        --purge)      PURGE=true; shift ;;
        -h|--help)
            echo "Usage: sudo bash uninstall.sh [--deploy-dir PATH] [--purge]"
            echo ""
            echo "  --deploy-dir PATH   Specify Nexus installation directory"
            echo "  --purge             Also remove the deploy directory and venv"
            echo ""
            echo "  Note: MySQL database is NEVER deleted automatically."
            exit 0 ;;
        *) shift ;;
    esac
done

# Auto-detect deploy directory
if [ -z "$DEPLOY_DIR" ]; then
    for d in /opt/nexus /www/wwwroot/*/; do
        if [ -d "$d/server" ] && [ -d "$d/web" ]; then
            DEPLOY_DIR="$d"
            break
        fi
    done
fi

if [ -z "$DEPLOY_DIR" ] || [ ! -d "$DEPLOY_DIR/server" ]; then
    error "Cannot find Nexus installation. Use --deploy-dir to specify."
    exit 1
fi

# Detect BT Panel
BT_MODE=false
if [ -d "/www/server/panel" ] && [ -f "/www/server/panel/class/common.py" ]; then
    BT_MODE=true
fi

echo ""
echo "=========================================="
echo "  Nexus 6.0 Uninstall"
echo "=========================================="
echo "  Deploy: $DEPLOY_DIR"
echo "  BT Panel: $BT_MODE"
echo "  Purge files: $PURGE"
echo ""

# Confirm
read -rp "Are you sure you want to uninstall Nexus? [y/N] " confirm
if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
    echo "Cancelled."
    exit 0
fi

# 1. Stop Supervisor process
info "Step 1/5: Stopping Nexus process..."
supervisorctl stop nexus >/dev/null 2>&1 || true

# 2. Remove Supervisor config
info "Step 2/5: Removing Supervisor config..."
if [ "$BT_MODE" = true ]; then
    SUPERVISOR_CONF="/www/server/panel/plugin/supervisor/profile/nexus.ini"
else
    SUPERVISOR_CONF="/etc/supervisor/conf.d/nexus.conf"
fi
if [ -f "$SUPERVISOR_CONF" ]; then
    rm -f "$SUPERVISOR_CONF"
    supervisorctl reread >/dev/null 2>&1 || true
    supervisorctl update >/dev/null 2>&1 || true
    info "  Removed $SUPERVISOR_CONF"
else
    info "  Supervisor config not found (already removed)"
fi

# 3. Remove Nginx config
info "Step 3/5: Removing Nginx config..."
if [ "$BT_MODE" = true ]; then
    # Find the domain from deploy dir
    DOMAIN=$(basename "$DEPLOY_DIR")
    NGINX_CONF="/www/server/panel/vhost/nginx/$DOMAIN.conf"
else
    NGINX_CONF="/etc/nginx/sites-available/nexus"
    NGINX_SYMLINK="/etc/nginx/sites-enabled/nexus"
fi

if [ -f "$NGINX_CONF" ]; then
    rm -f "$NGINX_CONF"
    [ -L "${NGINX_SYMLINK:-}" ] && rm -f "$NGINX_SYMLINK"
    if [ "$BT_MODE" = true ]; then
        /www/server/nginx/sbin/nginx -s reload >/dev/null 2>&1 || true
    else
        nginx -t >/dev/null 2>&1 && systemctl reload nginx 2>/dev/null || true
    fi
    info "  Removed $NGINX_CONF"
else
    info "  Nginx config not found (already removed)"
fi

# 4. Remove crontab entries
info "Step 4/5: Removing crontab entries..."
crontab -l 2>/dev/null | grep -v "health_monitor.sh" | grep -v "db_backup.sh" | crontab - 2>/dev/null || true
info "  Crontab entries removed"

# 5. Optionally remove deploy directory
if [ "$PURGE" = true ]; then
    info "Step 5/5: Removing deploy directory (--purge)..."
    rm -rf "$DEPLOY_DIR"
    info "  Removed $DEPLOY_DIR"
else
    info "Step 5/5: Keeping deploy directory (use --purge to remove)"
    info "  To remove manually: rm -rf $DEPLOY_DIR"
fi

echo ""
echo -e "  ${GREEN}Nexus uninstalled successfully.${NC}"
echo ""
echo "  Note: MySQL database was NOT deleted."
echo "  To drop the database manually:"
echo "    mysql -u root -e 'DROP DATABASE IF EXISTS nexus;'"
echo ""
