#!/bin/bash
#
# AtlasOS - Calypso Appliance Uninstaller
#
# Usage: sudo ./installer/alpha/uninstall.sh [options]
#
# Options:
#   --keep-data        Keep data directories and database
#   --keep-config      Keep configuration files
#

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

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

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check root
if [[ $EUID -ne 0 ]]; then
    log_error "This script must be run as root (use sudo)"
    exit 1
fi

KEEP_DATA=false
KEEP_CONFIG=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --keep-data)
            KEEP_DATA=true
            shift
            ;;
        --keep-config)
            KEEP_CONFIG=true
            shift
            ;;
        *)
            log_error "Unknown option: $1"
            exit 1
            ;;
    esac
done

log_info "=========================================="
log_info "Calypso Appliance Uninstaller"
log_info "=========================================="
log_info ""

# Confirm
read -p "Are you sure you want to uninstall Calypso? (yes/no): " confirm
if [[ "$confirm" != "yes" ]]; then
    log_info "Uninstallation cancelled"
    exit 0
fi

# Stop services
log_info "Stopping services..."
systemctl stop calypso-api 2>/dev/null || true
systemctl disable calypso-api 2>/dev/null || true

# Remove systemd services
log_info "Removing systemd services..."
rm -f /etc/systemd/system/calypso-api.service
rm -rf /etc/systemd/system/calypso-api.service.d/
systemctl daemon-reload

# Remove binaries
log_info "Removing binaries..."
rm -rf /opt/adastra/calypso

# Remove configuration
if [[ "$KEEP_CONFIG" == "false" ]]; then
    log_info "Removing configuration..."
    rm -rf /etc/calypso
else
    log_info "Keeping configuration files (--keep-config)"
fi

# Remove data
if [[ "$KEEP_DATA" == "false" ]]; then
    log_info "Removing data directories..."
    rm -rf /srv/calypso
    rm -rf /var/lib/calypso
    rm -rf /var/log/calypso
    rm -rf /run/calypso
else
    log_info "Keeping data directories (--keep-data)"
fi

# Remove user (optional)
read -p "Remove calypso user? (y/N): " remove_user
if [[ "$remove_user" =~ ^[Yy]$ ]]; then
    userdel calypso 2>/dev/null || true
    log_info "User removed"
fi

log_info ""
log_info "=========================================="
log_info "Uninstallation Complete"
log_info "=========================================="
log_info ""

if [[ "$KEEP_DATA" == "true" ]] || [[ "$KEEP_CONFIG" == "true" ]]; then
    log_warn "Some files were kept. Manual cleanup may be required."
fi

