#!/bin/bash
# Gateway Type 3 - Remove systemd Service
# Removes the gateway systemd service
#
# Usage: sudo bash remove-service.sh
# Output: RESULT:removed=true|false

set -e

# Get script directory and project directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# If running from node_modules, find the actual install dir
if [[ "$PROJECT_DIR" == *"node_modules"* ]]; then
    INSTALL_DIR="$(cd "$PROJECT_DIR/../.." && pwd)"
else
    INSTALL_DIR="$PROJECT_DIR"
fi

# Configuration
SERVICE_NAME="langmart-gateway"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

# Log function
log() {
    local level="${2:-INFO}"
    local timestamp=$(date +"%H:%M:%S")
    echo "[$level] $timestamp - $1"
}

log "=== Gateway Type 3 Remove Service ==="
log "Install directory: $INSTALL_DIR"

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    log "This script must be run as root (use sudo)" "ERROR"
    echo "RESULT:removed=false"
    exit 1
fi

# Check if systemd is available
if ! command -v systemctl &> /dev/null; then
    log "systemd not found" "ERROR"
    echo "RESULT:removed=false"
    exit 1
fi

# Check if service exists
if [ ! -f "$SERVICE_FILE" ]; then
    log "Service not installed (no service file found)" "WARN"
    # Remove marker file if exists
    rm -f "$INSTALL_DIR/.service-mode"
    echo "RESULT:removed=true"
    exit 0
fi

log "Stopping service..."
systemctl stop "$SERVICE_NAME" 2>/dev/null || true

log "Disabling service..."
systemctl disable "$SERVICE_NAME" 2>/dev/null || true

log "Removing service file..."
rm -f "$SERVICE_FILE"

log "Reloading systemd daemon..."
systemctl daemon-reload

# Remove service marker file
rm -f "$INSTALL_DIR/.service-mode"

log "Service removed successfully" "SUCCESS"
log ""
log "The gateway can still be run manually:"
log "  bash $SCRIPT_DIR/start.sh"

echo "RESULT:removed=true"
exit 0
