#!/bin/bash
# Linux Service Uninstall Script for Cosmos Cloud
# This script removes only the VPN service, not the application

set -e

APP_NAME="Cosmos Cloud"
SERVICE_NAME="ConstellationService"
# The unit is always installed system-wide by the Go service (see go/desktop/desktop.go)
SERVICE_UNIT="/etc/systemd/system/$SERVICE_NAME.service"
# Space-free copy of the service binary made at install time
DEPLOYED_BINARY="/var/cosmos-vpn/bin/constellation"

echo "=== Removing $APP_NAME VPN Service ==="

# Function to check if running as root
check_root() {
    if [[ $EUID -eq 0 ]]; then
        return 0
    else
        return 1
    fi
}

# Stop and remove service
cleanup_service() {
    echo "Cleaning up VPN service..."
    
    # Try to find constellation binary in common locations (both architectures,
    # plus the copy the installer deploys to a space-free path)
    POSSIBLE_LOCATIONS=()
    for arch in amd64 arm64; do
        POSSIBLE_LOCATIONS+=(
            "$(dirname "$0")/constellation-linux-$arch"
            "$(dirname "$0")/data/flutter_assets/resources/constellation-linux-$arch"
            "./constellation-linux-$arch"
            "./data/flutter_assets/resources/constellation-linux-$arch"
        )
    done
    POSSIBLE_LOCATIONS+=("$DEPLOYED_BINARY")

    CONSTELLATION_BINARY=""
    for location in "${POSSIBLE_LOCATIONS[@]}"; do
        if [[ -f "$location" ]]; then
            CONSTELLATION_BINARY="$location"
            echo "Found constellation binary at: $location"
            break
        fi
    done

    if [[ -n "$CONSTELLATION_BINARY" ]]; then
        echo "Using constellation binary to remove service..."

        # Note: do NOT swallow stderr - it carries the actual reason for failure
        # (e.g. "could not obtain administrator privileges").
        if "$CONSTELLATION_BINARY" stop; then
            echo "Service stopped successfully"
        else
            echo "Warning: Failed to stop service (might not be running)"
        fi

        # Remove the service
        if "$CONSTELLATION_BINARY" remove; then
            echo "Service removed successfully"
        else
            echo "Warning: Failed to remove service (might not be installed)"
        fi

        # Wait for cleanup
        sleep 2
    else
        echo "Constellation binary not found, trying systemd cleanup..."
    fi

    # Always verify the system unit is really gone: the binary may have failed to
    # elevate, or kardianos/service may have bailed out before removing the file.
    cleanup_systemd_unit
}

# The unit is installed system-wide, so only the system scope is checked here.
cleanup_systemd_unit() {
    if ! command -v systemctl >/dev/null 2>&1; then
        return 0
    fi

    if [[ ! -f "$SERVICE_UNIT" ]] && ! systemctl is-active "$SERVICE_NAME" >/dev/null 2>&1; then
        return 0
    fi

    if ! check_root; then
        echo "Leftover system service detected but root privileges are required to remove it."
        echo "Please run: sudo $0"
        return 0
    fi

    echo "Cleaning up system service unit..."
    systemctl stop "$SERVICE_NAME" 2>/dev/null || true
    systemctl disable "$SERVICE_NAME" 2>/dev/null || true

    if [[ -f "$SERVICE_UNIT" ]]; then
        rm -f "$SERVICE_UNIT"
        echo "Removed unit file: $SERVICE_UNIT"
    fi

    systemctl daemon-reload 2>/dev/null || true
    systemctl reset-failed "$SERVICE_NAME" 2>/dev/null || true

    if [[ -f "$DEPLOYED_BINARY" ]]; then
        rm -f "$DEPLOYED_BINARY"
        echo "Removed deployed service binary: $DEPLOYED_BINARY"
    fi
}

# Clean up service data (optional, ask user)
cleanup_service_data() {
    SERVICE_DATA_DIR="/var/cosmos-vpn"
    
    if [[ -d "$SERVICE_DATA_DIR" ]]; then
        echo
        read -p "Remove VPN service data and logs? [y/N]: " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            if check_root; then
                rm -rf "$SERVICE_DATA_DIR"
                echo "Removed service data directory: $SERVICE_DATA_DIR"
            else
                echo "Root privileges required to remove service data."
                echo "You can manually remove: $SERVICE_DATA_DIR"
            fi
        else
            echo "Service data preserved at: $SERVICE_DATA_DIR"
        fi
    fi
}

# Main service removal process
main() {
    echo "This will remove the $APP_NAME VPN service from your system."
    echo "The application itself will remain installed."
    echo
    read -p "Are you sure you want to continue? [y/N]: " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Service removal cancelled."
        exit 0
    fi
    
    cleanup_service
    cleanup_service_data
    
    echo
    echo "=== VPN Service removal completed successfully! ==="
    echo "The application is still installed but the background service has been removed."
    echo "You can safely delete this application folder if you no longer need it."
}

# Check if script is being sourced (for testing)
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi