#!/bin/bash
# ============================================
# Git Pusher - Start Script
# Version 2.0 avec système de licence
# ============================================

# Configuration
SPLUNK_HOME=${SPLUNK_HOME:-/opt/splunk}
APP_HOME="${SPLUNK_HOME}/etc/apps/pusher_app_prem"
BIN_DIR="${APP_HOME}/bin"
LOG_DIR="${SPLUNK_HOME}/var/log/splunk"
PID_FILE="${BIN_DIR}/git_pusher.pid"

# Couleurs pour les logs
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

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

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

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

# Vérifier si le serveur est déjà en cours d'exécution
check_running() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p $PID > /dev/null 2>&1; then
            return 0  # Running
        fi
    fi
    return 1  # Not running
}

# Démarrer le serveur
start_server() {
    log_info "Starting Git Pusher server..."
    
    # Vérifier si déjà en cours
    if check_running; then
        log_warn "Git Pusher is already running (PID: $(cat $PID_FILE))"
        return 1
    fi
    
    # Créer le répertoire de logs
    mkdir -p "$LOG_DIR"
    
    # Variables d'environnement pour l'authentification Splunk
    # IMPORTANT: Modifiez ces valeurs ou utilisez des variables d'environnement
    export SPLUNK_USERNAME=${SPLUNK_USERNAME:-admin}
    export SPLUNK_PASSWORD=${SPLUNK_PASSWORD:-changeme}
    
    # Démarrer le serveur Python
    cd "$BIN_DIR"
    python3 git_pusher.py > "${LOG_DIR}/git_pusher_startup.log" 2>&1 &
    
    # Sauvegarder le PID
    echo $! > "$PID_FILE"
    
    # Attendre un peu et vérifier
    sleep 2
    
    if check_running; then
        log_info "Git Pusher started successfully (PID: $(cat $PID_FILE))"
        log_info "Server listening on port 9999"
        
        # Vérifier le statut de la licence
        HOSTNAME=$(hostname)
        log_info "Hostname: $HOSTNAME"
        
        if [ -f "${APP_HOME}/local/license.lic" ]; then
            log_info "License file found"
        else
            log_warn "No license file found at ${APP_HOME}/local/license.lic"
            log_warn "The application will require license activation"
        fi
        
        return 0
    else
        log_error "Failed to start Git Pusher"
        log_error "Check logs at ${LOG_DIR}/git_pusher.log"
        return 1
    fi
}

# Arrêter le serveur
stop_server() {
    log_info "Stopping Git Pusher server..."
    
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        
        if ps -p $PID > /dev/null 2>&1; then
            kill $PID
            sleep 2
            
            # Force kill si nécessaire
            if ps -p $PID > /dev/null 2>&1; then
                log_warn "Force killing process..."
                kill -9 $PID
            fi
            
            rm -f "$PID_FILE"
            log_info "Git Pusher stopped"
            return 0
        else
            log_warn "Process not running, cleaning up PID file"
            rm -f "$PID_FILE"
            return 0
        fi
    else
        log_warn "PID file not found, Git Pusher may not be running"
        return 1
    fi
}

# Redémarrer le serveur
restart_server() {
    log_info "Restarting Git Pusher server..."
    stop_server
    sleep 1
    start_server
}

# Afficher le statut
show_status() {
    echo "============================================"
    echo "Git Pusher Status"
    echo "============================================"
    
    if check_running; then
        PID=$(cat "$PID_FILE")
        echo -e "Status: ${GREEN}RUNNING${NC}"
        echo "PID: $PID"
        echo "Port: 9999"
    else
        echo -e "Status: ${RED}STOPPED${NC}"
    fi
    
    echo ""
    echo "Paths:"
    echo "  App Home: $APP_HOME"
    echo "  Bin Dir: $BIN_DIR"
    echo "  Log Dir: $LOG_DIR"
    echo ""
    
    # Statut de la licence
    echo "License:"
    if [ -f "${APP_HOME}/local/license.lic" ]; then
        echo -e "  File: ${GREEN}Present${NC}"
        # Essayer de lire quelques infos
        if command -v python3 &> /dev/null; then
            python3 -c "
import sys
sys.path.insert(0, '$BIN_DIR')
from license_validator import validate_license
result = validate_license()
if result.get('valid'):
    print(f\"  Type: {result.get('type_name', 'N/A')}\")
    print(f\"  Expires: {result.get('expires', 'N/A')}\")
    print(f\"  Days remaining: {result.get('days_remaining', 'N/A')}\")
else:
    print(f\"  Status: Invalid - {result.get('error', 'Unknown error')}\")
" 2>/dev/null || echo "  Unable to read license details"
        fi
    else
        echo -e "  File: ${YELLOW}Not found${NC}"
    fi
    
    echo ""
    echo "Hostname: $(hostname)"
    echo "============================================"
}

# Afficher les logs
show_logs() {
    LOG_FILE="${LOG_DIR}/git_pusher.log"
    
    if [ -f "$LOG_FILE" ]; then
        if [ "$1" == "-f" ]; then
            tail -f "$LOG_FILE"
        else
            tail -n 50 "$LOG_FILE"
        fi
    else
        log_warn "Log file not found at $LOG_FILE"
    fi
}

# Menu d'aide
show_help() {
    echo "Git Pusher - Server Management Script"
    echo ""
    echo "Usage: $0 {start|stop|restart|status|logs|help}"
    echo ""
    echo "Commands:"
    echo "  start    Start the Git Pusher server"
    echo "  stop     Stop the Git Pusher server"
    echo "  restart  Restart the Git Pusher server"
    echo "  status   Show the current status"
    echo "  logs     Show recent logs (use -f for follow)"
    echo "  help     Show this help message"
    echo ""
    echo "Environment variables:"
    echo "  SPLUNK_USERNAME  Splunk admin username (default: admin)"
    echo "  SPLUNK_PASSWORD  Splunk admin password (default: changeme)"
    echo "  SPLUNK_HOME      Splunk installation directory (default: /opt/splunk)"
}

# Main
case "$1" in
    start)
        start_server
        ;;
    stop)
        stop_server
        ;;
    restart)
        restart_server
        ;;
    status)
        show_status
        ;;
    logs)
        show_logs "$2"
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        # Par défaut, démarrer le serveur (pour compatibilité)
        if [ -z "$1" ]; then
            start_server
        else
            echo "Unknown command: $1"
            show_help
            exit 1
        fi
        ;;
esac
