#!/bin/bash

# SAM System-wide Installation Script
# Based on sam.spec installation requirements
# Only use for testing purposes, not for production
# For production use the rpm package
# Vibe coded with Cursor/Claude4

set -e  # Exit on any error

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
SADB_SOURCE_DIR="${REPO_DIR}/saDB"

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

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

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

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

# Handle command line arguments first (before root check)
if [[ "$1" == "--help" || "$1" == "-h" ]]; then
    echo "SAM System-wide Installation Script"
    echo ""
    echo "Usage:"
    echo "  sudo $0           Install SAM system-wide"
    echo "  sudo $0 --uninstall   Uninstall SAM"
    echo "  sudo $0 --help        Show this help message"
    exit 0
fi

# Check if running as root
if [[ $EUID -ne 0 ]]; then
    print_error "This script must be run as root for system-wide installation"
    echo "Usage: sudo $0 [--uninstall]"
    exit 1
fi

# Get Python3 site-packages directory
PYTHON3_SITELIB=$(python3 -c "import site; print(site.getsitepackages()[0])")
if [[ -z "$PYTHON3_SITELIB" ]]; then
    print_error "Could not determine Python3 site-packages directory"
    exit 1
fi

# Define installation directories
BINDIR="/usr/bin"
UNITDIR="/usr/lib/systemd/system"
PRESETDIR="/usr/lib/systemd/system-preset"
DBUSCONFDIR="/etc/dbus-1/system.d"
STATEDIR="/var/lib/sam"
SAM_SITELIB="$PYTHON3_SITELIB/sam"
SADB_SITELIB="$PYTHON3_SITELIB/sadb"

# Uninstall function
uninstall_sam() {
    print_status "Starting SAM uninstallation..."

    # Stop and disable service
    if systemctl is-active --quiet sam.service; then
        print_status "Stopping SAM service..."
        systemctl stop sam.service
    fi

    if systemctl is-enabled --quiet sam.service; then
        print_status "Disabling SAM service..."
        systemctl disable sam.service
    fi

    # Remove files
    print_status "Removing installed files..."
    
    if [[ -f "$BINDIR/sam" ]]; then
        rm -f "$BINDIR/sam"
        print_status "Removed $BINDIR/sam"
    fi

    if [[ -d "$SAM_SITELIB" ]]; then
        rm -rf "$SAM_SITELIB"
        print_status "Removed $SAM_SITELIB"
    fi

    if [[ -d "$SADB_SITELIB" ]]; then
        rm -rf "$SADB_SITELIB"
        print_status "Removed $SADB_SITELIB"
    fi

    if [[ -f "$UNITDIR/sam.service" ]]; then
        rm -f "$UNITDIR/sam.service"
        print_status "Removed $UNITDIR/sam.service"
    fi

    if [[ -f "$PRESETDIR/95-sam.preset" ]]; then
        rm -f "$PRESETDIR/95-sam.preset"
        print_status "Removed $PRESETDIR/95-sam.preset"
    fi

    if [[ -f "$DBUSCONFDIR/io.stillhq.sam.conf" ]]; then
        rm -f "$DBUSCONFDIR/io.stillhq.sam.conf"
        print_status "Removed $DBUSCONFDIR/io.stillhq.sam.conf"
    fi

    # Reload systemd and D-Bus
    print_status "Reloading systemd daemon..."
    systemctl daemon-reload

    print_status "Reloading D-Bus configuration..."
    if systemctl is-active --quiet dbus; then
        systemctl reload dbus
    fi

    print_status "SAM has been successfully uninstalled!"
}

# Handle uninstall command
if [[ "$1" == "--uninstall" ]]; then
    uninstall_sam
    exit 0
fi

print_status "Python3 site-packages directory: $PYTHON3_SITELIB"

print_status "Starting SAM system-wide installation..."

# Check dependencies
print_status "Checking dependencies..."
MISSING_DEPS=()

# Check for required Python packages
if ! python3 -c "import pydbus" 2>/dev/null; then
    MISSING_DEPS+=("python3-pydbus")
fi

if ! python3 -c "import gi" 2>/dev/null; then
    MISSING_DEPS+=("python3-gobject")
fi

# Check for libappstream-glib
if ! ldconfig -p | grep -q libappstream-glib; then
    MISSING_DEPS+=("libappstream-glib")
fi

if [[ ${#MISSING_DEPS[@]} -gt 0 ]]; then
    print_warning "Missing dependencies detected:"
    for dep in "${MISSING_DEPS[@]}"; do
        echo "  - $dep"
    done
    print_warning "Please install these dependencies before running SAM"
fi

# Create installation directories
print_status "Creating installation directories..."
mkdir -p "$SAM_SITELIB"
mkdir -p "$SAM_SITELIB/managers"
mkdir -p "$SADB_SITELIB"
mkdir -p "$SADB_SITELIB/source"
mkdir -p "$UNITDIR"
mkdir -p "$PRESETDIR"
mkdir -p "$DBUSCONFDIR"
mkdir -p "$STATEDIR"

# Install Python files
print_status "Installing Python modules..."
install -m 0644 "${SCRIPT_DIR}"/*.py "$SAM_SITELIB/"
cp -a "${SCRIPT_DIR}/managers/"*.py "$SAM_SITELIB/managers/"

print_status "Installing local SADB modules..."
install -m 0644 "${SADB_SOURCE_DIR}/src/"*.py "$SADB_SITELIB/"
cp -a "${SADB_SOURCE_DIR}/src/source/"*.py "$SADB_SITELIB/source/"

# Install main executable
print_status "Installing main executable..."
install -m 0755 "${SCRIPT_DIR}/__main__.py" "$BINDIR/sam"

# Install systemd service file
print_status "Installing systemd service..."
install -m 0644 "${SCRIPT_DIR}/systemd/sam.service" "$UNITDIR/"

# Install systemd preset
print_status "Installing systemd preset..."
install -m 0644 "${SCRIPT_DIR}/systemd/95-sam.preset" "$PRESETDIR/"

# Install D-Bus configuration
print_status "Installing D-Bus configuration..."
install -m 0644 "${SCRIPT_DIR}/io.stillhq.sam.conf" "$DBUSCONFDIR/"

# Reload systemd and D-Bus
print_status "Reloading systemd daemon..."
systemctl daemon-reload

print_status "Reloading D-Bus configuration..."
if systemctl is-active --quiet dbus; then
    systemctl reload dbus
else
    print_warning "D-Bus service is not running, configuration will be loaded on next start"
fi

# Enable and start/restart the service
print_status "Enabling SAM service..."
systemctl preset sam.service
systemctl enable sam.service

# Check if SAM is already running and restart if so, otherwise start it
if systemctl is-active --quiet sam.service; then
    print_status "SAM service is already running, restarting..."
    if systemctl restart sam.service; then
        print_status "SAM service restarted successfully"
    else
        print_warning "Failed to restart SAM service. Check logs with: journalctl -u sam.service"
    fi
else
    print_status "Starting SAM service..."
    if systemctl start sam.service; then
        print_status "SAM service started successfully"
    else
        print_warning "Failed to start SAM service. Check logs with: journalctl -u sam.service"
    fi
fi

# Verify installation
print_status "Verifying installation..."
INSTALL_SUCCESS=true

# Check if files are installed
if [[ ! -f "$BINDIR/sam" ]]; then
    print_error "Main executable not found at $BINDIR/sam"
    INSTALL_SUCCESS=false
fi

if [[ ! -d "$SAM_SITELIB" ]]; then
    print_error "Python module directory not found at $SAM_SITELIB"
    INSTALL_SUCCESS=false
fi

if [[ ! -d "$SADB_SITELIB" ]]; then
    print_error "SADB module directory not found at $SADB_SITELIB"
    INSTALL_SUCCESS=false
fi

if [[ ! -f "$UNITDIR/sam.service" ]]; then
    print_error "Systemd service file not found at $UNITDIR/sam.service"
    INSTALL_SUCCESS=false
fi

# Check service status
if systemctl is-enabled --quiet sam.service; then
    print_status "SAM service is enabled"
else
    print_warning "SAM service is not enabled"
    INSTALL_SUCCESS=false
fi

if systemctl is-active --quiet sam.service; then
    print_status "SAM service is running"
else
    print_warning "SAM service is not running"
fi

echo
echo "================================"
if [[ "$INSTALL_SUCCESS" == "true" ]]; then
    print_status "SAM has been successfully installed system-wide!"
else
    print_warning "SAM installation completed with some issues"
fi

echo
echo "Installation summary:"
echo "  • Executable: $BINDIR/sam"
echo "  • Python modules: $SAM_SITELIB"
echo "  • SADB modules: $SADB_SITELIB"
echo "  • Systemd service: $UNITDIR/sam.service"
echo "  • D-Bus config: $DBUSCONFDIR/io.stillhq.sam.conf"
echo
echo "To manage the SAM service:"
echo "  • Start:   sudo systemctl start sam.service"
echo "  • Stop:    sudo systemctl stop sam.service"
echo "  • Status:  sudo systemctl status sam.service"
echo "  • Logs:    sudo journalctl -u sam.service"
echo
echo "To uninstall SAM, run: sudo $0 --uninstall"
echo "================================" 
