#!/bin/bash

# C Nostr Relay Event-Based Configuration System - Uninstall Script
# This script removes the C Nostr Relay systemd service

set -e

# Configuration
SERVICE_NAME="c-relay"
SERVICE_USER="c-relay"
INSTALL_DIR="/opt/c-relay"

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

# Function to print colored output
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

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

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    print_error "This script must be run as root"
    exit 1
fi

print_info "Uninstalling C Nostr Relay Event-Based Configuration System"
echo

# Stop and disable service
if systemctl is-active --quiet "${SERVICE_NAME}"; then
    print_info "Stopping ${SERVICE_NAME} service"
    systemctl stop "${SERVICE_NAME}"
fi

if systemctl is-enabled --quiet "${SERVICE_NAME}"; then
    print_info "Disabling ${SERVICE_NAME} service"
    systemctl disable "${SERVICE_NAME}"
fi

# Remove systemd service file
if [ -f "/etc/systemd/system/${SERVICE_NAME}.service" ]; then
    print_info "Removing systemd service file"
    rm "/etc/systemd/system/${SERVICE_NAME}.service"
fi

# Reload systemd
print_info "Reloading systemd daemon"
systemctl daemon-reload
systemctl reset-failed

# Ask about removing installation directory and databases
echo
print_warning "The installation directory ${INSTALL_DIR} contains:"
echo "  • The relay binary"
echo "  • Database files with all events and configuration (.nrdb files)"
echo "  • Any logs or temporary files"
echo
read -p "Do you want to remove ${INSTALL_DIR} and all data? [y/N]: " -r
if [[ $REPLY =~ ^[Yy]$ ]]; then
    print_info "Removing installation directory: ${INSTALL_DIR}"
    rm -rf "${INSTALL_DIR}"
    print_success "Installation directory removed"
else
    print_info "Installation directory preserved: ${INSTALL_DIR}"
    print_warning "Database files (.nrdb) are preserved and contain all relay data"
fi

# Ask about removing service user
echo
read -p "Do you want to remove the service user '${SERVICE_USER}'? [y/N]: " -r
if [[ $REPLY =~ ^[Yy]$ ]]; then
    if id "${SERVICE_USER}" &>/dev/null; then
        print_info "Removing service user: ${SERVICE_USER}"
        userdel "${SERVICE_USER}" 2>/dev/null || print_warning "Could not remove user ${SERVICE_USER}"
        print_success "Service user removed"
    else
        print_info "Service user ${SERVICE_USER} does not exist"
    fi
else
    print_info "Service user '${SERVICE_USER}' preserved"
fi

print_success "Uninstallation complete!"
echo
print_info "If you preserved the database files, you can reinstall and the relay will"
print_info "automatically detect the existing configuration and continue with the same keys."