#!/bin/bash
set -e

# NexusGuard Server Uninstaller

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

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

# Check root
if [ "$EUID" -ne 0 ]; then
    error "Please run as root"
fi

SERVICE_NAME="nexusguard-server"
CONF_DIR="/etc/nexusguard"
CONF_FILE="$CONF_DIR/nexusguard.conf"
NGINX_CONF="/etc/nginx/conf.d/nexusguard.conf"
DASHBOARD_DIR="/usr/share/nexusguard/dashboard"
BINARY_DIR="/usr/local/bin"

REMOVE_DB=false
while [[ "$#" -gt 0 ]]; do
    case $1 in
        --remove-db) REMOVE_DB=true; shift ;;
        *) error "Unknown parameter: $1" ;;
    esac
done

info "Uninstalling NexusGuard Server..."

# Stop and disable service
if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
    info "Stopping service..."
    systemctl stop "$SERVICE_NAME"
fi

if systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null; then
    info "Disabling service..."
    systemctl disable "$SERVICE_NAME"
fi

# Remove files
info "Removing files..."

if [ -f "$BINARY_DIR/$SERVICE_NAME" ]; then
    rm -f "$BINARY_DIR/$SERVICE_NAME"
    info "Removed binary: $BINARY_DIR/$SERVICE_NAME"
fi

if [ -d "$DASHBOARD_DIR" ]; then
    rm -rf "$DASHBOARD_DIR"
    info "Removed dashboard: $DASHBOARD_DIR"
fi

if [ -f "$CONF_FILE" ]; then
    rm -f "$CONF_FILE"
    info "Removed config: $CONF_FILE"
fi

if [ -d "$CONF_DIR" ]; then
    rmdir "$CONF_DIR" 2>/dev/null || true
    info "Removed config directory: $CONF_DIR"
fi

if [ -f "/etc/systemd/system/$SERVICE_NAME.service" ]; then
    rm -f "/etc/systemd/system/$SERVICE_NAME.service"
    info "Removed systemd service"
fi

if [ -f "$NGINX_CONF" ]; then
    rm -f "$NGINX_CONF"
    info "Removed nginx config: $NGINX_CONF"
fi

if [ "$REMOVE_DB" = true ]; then
    info "Removing PostgreSQL database and user..."
    psql -U postgres -c "DROP DATABASE IF EXISTS nexusguard;" 2>/dev/null || true
    psql -U postgres -c "DROP USER IF EXISTS nexusguard;" 2>/dev/null || true
    info "Database and user removed."
fi

# Reload systemd and nginx
info "Reloading systemd daemon..."
systemctl daemon-reload

if command -v nginx >/dev/null 2>&1; then
    info "Reloading nginx..."
    nginx -t && systemctl reload nginx 2>/dev/null || true
fi

info "Uninstall complete!"
echo ""
info "NexusGuard has been removed."
if [ "$REMOVE_DB" = false ]; then
    info "Note: PostgreSQL data was NOT removed."
    info "To also remove database: $0 --remove-db"
fi
