#!/bin/bash
# ============================================================
# WinLab Monitor - Script di Installazione Automatico (Linux)
# ============================================================

set -eu

# Colori per output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Funzioni di utilità
print_header() {
    echo -e "${BLUE}============================================${NC}"
    echo -e "${BLUE}  WinLab Monitor - Installazione${NC}"
    echo -e "${BLUE}============================================${NC}"
    echo ""
}

print_success() {
    echo -e "${GREEN}[OK]${NC} $1"
}

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

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

print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

# Verifica Linux
if [[ "$(uname)" != "Linux" ]]; then
    print_error "Questo script è solo per Linux"
    exit 1
fi

# Verifica se eseguito come root (per installazione di sistema)
if [[ $EUID -eq 0 ]]; then
    INSTALL_TYPE="system"
    INSTALL_DIR="/usr/local/bin"
    SERVICE_FILE="/etc/systemd/system/winlab-monitor.service"
else
    INSTALL_TYPE="user"
    INSTALL_DIR="$HOME/.local/bin"
    SERVICE_FILE="$HOME/.config/systemd/user/winlab-monitor.service"
fi

print_header

# Trova l'eseguibile
EXE_PATH=""
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

if [[ -f "$SCRIPT_DIR/winlab-monitor-linux" ]]; then
    EXE_PATH="$SCRIPT_DIR/winlab-monitor-linux"
    print_success "Trovato: winlab-monitor-linux"
elif [[ -f "$SCRIPT_DIR/../public/downloads/winlab-monitor-linux" ]]; then
    EXE_PATH="$SCRIPT_DIR/../public/downloads/winlab-monitor-linux"
    print_success "Trovato: ../public/downloads/winlab-monitor-linux"
else
    print_error "Impossibile trovare winlab-monitor-linux"
    echo ""
    echo "Assicurati che il file sia nella stessa cartella di questo script"
    echo "o in ../public/downloads/"
    exit 1
fi

echo ""
echo -e "${BLUE}============================================${NC}"
echo -e "${BLUE}  Tipo di Installazione: ${INSTALL_TYPE}${NC}"
echo -e "${BLUE}============================================${NC}"
echo ""

if [[ "$INSTALL_TYPE" == "system" ]]; then
    print_info "Installazione di sistema (richiede root)"
    print_info "Directory: $INSTALL_DIR"
else
    print_info "Installazione utente (consigliata)"
    print_info "Directory: $INSTALL_DIR"
fi

echo ""
echo -e "${BLUE}============================================${NC}"
echo -e "${BLUE}  Creazione Directory${NC}"
echo -e "${BLUE}============================================${NC}"
echo ""

# Crea directory se non esiste
mkdir -p "$INSTALL_DIR"
if [[ ! -d "$INSTALL_DIR" ]]; then
    print_error "Impossibile creare directory: $INSTALL_DIR"
    exit 1
fi
print_success "Directory pronta: $INSTALL_DIR"

echo ""
echo -e "${BLUE}============================================${NC}"
echo -e "${BLUE}  Copia File${NC}"
echo -e "${BLUE}============================================${NC}"
echo ""

cp "$EXE_PATH" "$INSTALL_DIR/winlab-monitor"
chmod +x "$INSTALL_DIR/winlab-monitor"
print_success "Copiato e impostati permessi: winlab-monitor"

# Aggiungi a PATH se necessario
if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
    print_warning "$INSTALL_DIR non è nel PATH"
    echo "export PATH=\"\$PATH:$INSTALL_DIR\"" >> "$HOME/.bashrc"
    print_success "Aggiunto al PATH in ~/.bashrc"
    print_info "Esegui 'source ~/.bashrc' o riavvia il terminale"
fi

echo ""
echo -e "${BLUE}============================================${NC}"
echo -e "${BLUE}  Configurazione Servizio Systemd${NC}"
echo -e "${BLUE}============================================${NC}"
echo ""

read -p "Vuoi configurare WinLab Monitor come servizio systemd? (S/N): " CONFIGURE_SERVICE
if [[ "$CONFIGURE_SERVICE" =~ ^[Ss]$ ]]; then
    # Verifica systemd
    if ! command -v systemctl &> /dev/null; then
        print_warning "systemd non trovato, impossibile configurare servizio"
    else
        # Crea directory per servizio
        SERVICE_DIR=$(dirname "$SERVICE_FILE")
        mkdir -p "$SERVICE_DIR"

        # Crea file di servizio
        cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=WinLab Monitor - Monitoraggio documenti
After=network.target

[Service]
Type=simple
User=$USER
WorkingDirectory=$HOME/.winlab-monitor
ExecStart=$INSTALL_DIR/winlab-monitor
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

        if [[ "$INSTALL_TYPE" == "system" ]]; then
            # Installazione di sistema
            systemctl daemon-reload
            systemctl enable winlab-monitor
            print_success "Servizio systemd configurato e abilitato"
        else
            # Installazione utente
            systemctl --user daemon-reload
            systemctl --user enable winlab-monitor
            print_success "Servizio systemd utente configurato e abilitato"
        fi
    fi
else
    print_info "Servizio systemd non configurato"
fi

echo ""
echo -e "${BLUE}============================================${NC}"
echo -e "${BLUE}  Creazione Script di Avvio${NC}"
echo -e "${BLUE}============================================${NC}"
echo ""

cat > "$HOME/.winlab-monitor/start.sh" <<'EOF'
#!/bin/bash
cd "$HOME/.winlab-monitor"
"$HOME/.local/bin/winlab-monitor"
EOF

chmod +x "$HOME/.winlab-monitor/start.sh"
print_success "Creato script di avvio: $HOME/.winlab-monitor/start.sh"

echo ""
echo -e "${BLUE}============================================${NC}"
echo -e "${BLUE}  Installazione Completata!${NC}"
echo -e "${BLUE}============================================${NC}"
echo ""
echo "Directory installazione: $INSTALL_DIR"
echo "Eseguibile: $INSTALL_DIR/winlab-monitor"
echo ""
echo "Comandi disponibili:"
echo "  Avvio manuale:      $HOME/.winlab-monitor/start.sh"
echo "  Avvio diretto:      winlab-monitor"
echo "  Log del servizio:   journalctl -u winlab-monitor -f"
echo ""
if [[ "$CONFIGURE_SERVICE" =~ ^[Ss]$ ]] && command -v systemctl &> /dev/null; then
    echo "Gestione servizio:"
    if [[ "$INSTALL_TYPE" == "system" ]]; then
        echo "  Avvio servizio:     sudo systemctl start winlab-monitor"
        echo "  Stop servizio:      sudo systemctl stop winlab-monitor"
        echo "  Stato servizio:     sudo systemctl status winlab-monitor"
    else
        echo "  Avvio servizio:     systemctl --user start winlab-monitor"
        echo "  Stop servizio:      systemctl --user stop winlab-monitor"
        echo "  Stato servizio:     systemctl --user status winlab-monitor"
    fi
fi
echo ""
echo "Il monitor sarà disponibile su: http://localhost:3000"
echo ""

read -p "Vuoi avviare WinLab Monitor ora? (S/N): " LAUNCH
if [[ "$LAUNCH" =~ ^[Ss]$ ]]; then
    echo ""
    print_info "Avvio WinLab Monitor..."
    echo ""

    if [[ "$CONFIGURE_SERVICE" =~ ^[Ss]$ ]] && command -v systemctl &> /dev/null; then
        if [[ "$INSTALL_TYPE" == "system" ]]; then
            systemctl start winlab-monitor
        else
            systemctl --user start winlab-monitor
        fi
        print_success "Servizio avviato"
    else
        # Avvio in background
        nohup "$INSTALL_DIR/winlab-monitor" > "$HOME/.winlab-monitor/output.log" 2>&1 &
        print_success "Avviato in background"
        print_info "Log: $HOME/.winlab-monitor/output.log"
    fi

    sleep 2
    echo ""
    print_info "Apri il browser su: http://localhost:3000"
fi

echo ""
print_success "Installazione completata!"
echo ""
print_info "Per problemi, consulta: https://winlab.onexus.it/supporto"
echo ""