#!/bin/bash
# ============================================
# Git Pusher - Start Script
# Version 2.0 avec credentials sécurisés
# ============================================

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

# Couleurs pour les logs
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
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"
}

log_debug() {
    echo -e "${BLUE}[DEBUG]${NC} $1"
}

# Charger les credentials de manière sécurisée
load_credentials() {
    # Méthode 1: Utiliser le credentials manager (recommandé)
    if [ -f "$CREDENTIALS_MANAGER" ]; then
        CREDS=$(python3 "$CREDENTIALS_MANAGER" get 2>/dev/null)
        if [ $? -eq 0 ]; then
            export SPLUNK_USERNAME=$(echo "$CREDS" | head -1)
            export SPLUNK_PASSWORD=$(echo "$CREDS" | tail -1)
            log_info "Credentials loaded from secure storage"
            return 0
        fi
    fi
    
    # Méthode 2: Variables d'environnement déjà définies
    if [ -n "$SPLUNK_USERNAME" ] && [ -n "$SPLUNK_PASSWORD" ]; then
        log_info "Using credentials from environment variables"
        return 0
    fi
    
    # Méthode 3: Fichier .env (moins sécurisé mais pratique)
    ENV_FILE="${APP_HOME}/local/.env"
    if [ -f "$ENV_FILE" ]; then
        source "$ENV_FILE"
        if [ -n "$SPLUNK_USERNAME" ] && [ -n "$SPLUNK_PASSWORD" ]; then
            log_warn "Using credentials from .env file (consider using 'credentials setup' for better security)"
            return 0
        fi
    fi
    
    # Aucune credential trouvée
    log_error "No credentials found!"
    log_error "Please run: $0 credentials setup"
    return 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
}

# Configurer les credentials
setup_credentials() {
    if [ -f "$CREDENTIALS_MANAGER" ]; then
        python3 "$CREDENTIALS_MANAGER" setup
    else
        log_error "Credentials manager not found at $CREDENTIALS_MANAGER"
        exit 1
    fi
}

# Afficher le statut des credentials
credentials_status() {
    if [ -f "$CREDENTIALS_MANAGER" ]; then
        python3 "$CREDENTIALS_MANAGER" status
    else
        log_error "Credentials manager not found"
    fi
}

# Supprimer les credentials
delete_credentials() {
    if [ -f "$CREDENTIALS_MANAGER" ]; then
        python3 "$CREDENTIALS_MANAGER" delete
    else
        log_error "Credentials manager not found"
    fi
}

# 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
    
    # Charger les credentials
    if ! load_credentials; then
        exit 1
    fi
    
    # Créer le répertoire de logs
    mkdir -p "$LOG_DIR"
    
    # 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 - activation required"
        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 "Server Status: ${GREEN}RUNNING${NC}"
        echo "PID: $PID"
        echo "Port: 9999"
    else
        echo -e "Server 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 des credentials
    echo "Credentials:"
    if [ -f "${APP_HOME}/local/.credentials" ]; then
        echo -e "  Secure storage: ${GREEN}Configured${NC}"
    else
        echo -e "  Secure storage: ${YELLOW}Not configured${NC}"
    fi
    
    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')
try:
    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')}\")
except Exception as e:
    print(f'  Unable to read license: {e}')
" 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 v2.0"
    echo ""
    echo "Usage: $0 {command} [options]"
    echo ""
    echo "Server 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 [-f]          Show recent logs (-f for follow)"
    echo ""
    echo "Credentials Commands:"
    echo "  credentials setup  Configure Splunk credentials securely"
    echo "  credentials status Show credentials status"
    echo "  credentials delete Delete stored credentials"
    echo ""
    echo "Other:"
    echo "  help               Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 credentials setup   # First time setup"
    echo "  $0 start               # Start server"
    echo "  $0 logs -f             # Follow logs"
}

# Main
case "$1" in
    start)
        start_server
        ;;
    stop)
        stop_server
        ;;
    restart)
        restart_server
        ;;
    status)
        show_status
        ;;
    logs)
        show_logs "$2"
        ;;
    credentials)
        case "$2" in
            setup)
                setup_credentials
                ;;
            status)
                credentials_status
                ;;
            delete)
                delete_credentials
                ;;
            *)
                echo "Usage: $0 credentials {setup|status|delete}"
                ;;
        esac
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        if [ -z "$1" ]; then
            show_help
        else
            echo "Unknown command: $1"
            echo ""
            show_help
            exit 1
        fi
        ;;
esac