#!/bin/bash
# =============================================================================
# CashProxy macOS Installer Script
# =============================================================================
# Installa CashProxy e configura l'avvio automatico con launchd
# Uso: ./install-macos.sh [--uninstall] [--no-autostart] [--path /percorso]
# =============================================================================

set -e

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

# Configurazione
INSTALL_PATH="$HOME/Applications/CashProxy"
UPDATE_URL="https://download.qnegozio.svcfp.com/cashproxy/version.json"
LAUNCHD_LABEL="com.cashproxy.app"
LAUNCHD_PLIST="$HOME/Library/LaunchAgents/${LAUNCHD_LABEL}.plist"
AUTO_START=true
UNINSTALL=false

# Parse argomenti
while [[ $# -gt 0 ]]; do
    case $1 in
        --uninstall|-u)
            UNINSTALL=true
            shift
            ;;
        --no-autostart)
            AUTO_START=false
            shift
            ;;
        --path|-p)
            INSTALL_PATH="$2"
            shift 2
            ;;
        --help|-h)
            echo "Uso: $0 [opzioni]"
            echo ""
            echo "Opzioni:"
            echo "  --uninstall, -u     Disinstalla CashProxy"
            echo "  --no-autostart      Non configurare avvio automatico"
            echo "  --path, -p PATH     Percorso installazione (default: ~/Applications/CashProxy)"
            echo "  --help, -h          Mostra questo messaggio"
            exit 0
            ;;
        *)
            echo -e "${RED}Opzione sconosciuta: $1${NC}"
            exit 1
            ;;
    esac
done

echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  CashProxy macOS Installer${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Funzione disinstallazione
if [ "$UNINSTALL" = true ]; then
    echo -e "${YELLOW}Disinstallazione CashProxy...${NC}"

    # Ferma il servizio
    if launchctl list | grep -q "$LAUNCHD_LABEL"; then
        echo "Arresto servizio..."
        launchctl unload "$LAUNCHD_PLIST" 2>/dev/null || true
    fi

    # Rimuovi plist
    if [ -f "$LAUNCHD_PLIST" ]; then
        echo "Rimozione launchd plist..."
        rm -f "$LAUNCHD_PLIST"
    fi

    # Ferma processo
    pkill -f "CashProxy" 2>/dev/null || true

    # Chiedi conferma per rimuovere cartella
    echo ""
    read -p "Vuoi rimuovere anche la cartella $INSTALL_PATH? (s/N) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Ss]$ ]]; then
        rm -rf "$INSTALL_PATH"
        echo -e "${GREEN}Cartella rimossa${NC}"
    fi

    echo ""
    echo -e "${GREEN}Disinstallazione completata!${NC}"
    exit 0
fi

# Determina architettura
ARCH=$(uname -m)
if [ "$ARCH" = "arm64" ]; then
    PLATFORM="osx-arm64"
else
    PLATFORM="osx-x64"
fi
echo -e "${GREEN}Architettura:${NC} $PLATFORM"

# Scarica version.json
echo -e "${YELLOW}Verifica versione disponibile...${NC}"
VERSION=$(curl -s "$UPDATE_URL" | grep -o '"version": *"[^"]*"' | head -1 | cut -d'"' -f4)
if [ -z "$VERSION" ]; then
    echo -e "${RED}Errore: Impossibile ottenere la versione dal server${NC}"
    exit 1
fi
echo -e "${GREEN}  Versione disponibile: $VERSION${NC}"

# URL download
DOWNLOAD_URL="https://download.qnegozio.svcfp.com/cashproxy/releases/${VERSION}/CashProxy-${VERSION}-${PLATFORM}.zip"
ZIP_PATH="/tmp/CashProxy-${VERSION}.zip"

# Crea directory installazione
echo -e "${YELLOW}Creazione directory $INSTALL_PATH...${NC}"
mkdir -p "$INSTALL_PATH"

# Ferma eventuale processo in esecuzione
if pgrep -f "CashProxy" > /dev/null; then
    echo -e "${YELLOW}Arresto CashProxy in esecuzione...${NC}"
    pkill -f "CashProxy" 2>/dev/null || true
    sleep 2
fi

# Ferma servizio launchd se attivo
if launchctl list 2>/dev/null | grep -q "$LAUNCHD_LABEL"; then
    echo -e "${YELLOW}Arresto servizio launchd...${NC}"
    launchctl unload "$LAUNCHD_PLIST" 2>/dev/null || true
    sleep 1
fi

# Backup database esistente
DB_PATH="$INSTALL_PATH/Data/CashProxy.db"
BACKUP_DB="/tmp/CashProxy.db.backup"
if [ -f "$DB_PATH" ]; then
    echo -e "${YELLOW}Backup database esistente...${NC}"
    cp "$DB_PATH" "$BACKUP_DB"
    echo -e "${GREEN}  OK${NC}"
fi

# Backup certificati
CERT_PATH="$INSTALL_PATH/Certificates"
BACKUP_CERT="/tmp/CashProxy_Certificates_backup"
if [ -d "$CERT_PATH" ]; then
    echo -e "${YELLOW}Backup certificati esistenti...${NC}"
    cp -r "$CERT_PATH" "$BACKUP_CERT"
    echo -e "${GREEN}  OK${NC}"
fi

# Download
echo ""
echo -e "${YELLOW}Download CashProxy v${VERSION}...${NC}"
echo -e "  URL: $DOWNLOAD_URL"
curl -L -o "$ZIP_PATH" "$DOWNLOAD_URL" --progress-bar
FILE_SIZE=$(ls -lh "$ZIP_PATH" | awk '{print $5}')
echo -e "${GREEN}  Download completato ($FILE_SIZE)${NC}"

# Estrazione
echo -e "${YELLOW}Estrazione files...${NC}"
# Rimuovi vecchi file (tranne Data e Certificates)
find "$INSTALL_PATH" -mindepth 1 -maxdepth 1 ! -name "Data" ! -name "Certificates" -exec rm -rf {} \; 2>/dev/null || true

# Estrai ZIP
unzip -q -o "$ZIP_PATH" -d "$INSTALL_PATH"
rm -f "$ZIP_PATH"
echo -e "${GREEN}  OK${NC}"

# Ripristina database
if [ -f "$BACKUP_DB" ]; then
    echo -e "${YELLOW}Ripristino database...${NC}"
    mkdir -p "$INSTALL_PATH/Data"
    cp "$BACKUP_DB" "$DB_PATH"
    rm -f "$BACKUP_DB"
    echo -e "${GREEN}  OK${NC}"
fi

# Ripristina certificati
if [ -d "$BACKUP_CERT" ]; then
    echo -e "${YELLOW}Ripristino certificati...${NC}"
    rm -rf "$CERT_PATH"
    mv "$BACKUP_CERT" "$CERT_PATH"
    echo -e "${GREEN}  OK${NC}"
fi

# Rimuovi attributo quarantena (macOS Gatekeeper)
echo -e "${YELLOW}Rimozione quarantena macOS...${NC}"
xattr -cr "$INSTALL_PATH" 2>/dev/null || true
chmod +x "$INSTALL_PATH/CashProxy"
echo -e "${GREEN}  OK${NC}"

# Configura launchd per avvio automatico
if [ "$AUTO_START" = true ]; then
    echo ""
    echo -e "${YELLOW}Configurazione avvio automatico con launchd...${NC}"

    # Crea directory LaunchAgents se non esiste
    mkdir -p "$HOME/Library/LaunchAgents"

    # Crea plist
    cat > "$LAUNCHD_PLIST" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>${LAUNCHD_LABEL}</string>

    <key>ProgramArguments</key>
    <array>
        <string>${INSTALL_PATH}/CashProxy</string>
    </array>

    <key>WorkingDirectory</key>
    <string>${INSTALL_PATH}</string>

    <key>RunAtLoad</key>
    <true/>

    <key>KeepAlive</key>
    <dict>
        <key>SuccessfulExit</key>
        <false/>
        <key>Crashed</key>
        <true/>
    </dict>

    <key>ThrottleInterval</key>
    <integer>10</integer>

    <key>StandardOutPath</key>
    <string>${INSTALL_PATH}/logs/stdout.log</string>

    <key>StandardErrorPath</key>
    <string>${INSTALL_PATH}/logs/stderr.log</string>

    <key>EnvironmentVariables</key>
    <dict>
        <key>DOTNET_BUNDLE_EXTRACT_BASE_DIR</key>
        <string>${INSTALL_PATH}/.net</string>
        <key>ASPNETCORE_URLS</key>
        <string>http://localhost:5000;https://localhost:5001</string>
    </dict>
</dict>
</plist>
EOF

    # Crea directory logs
    mkdir -p "$INSTALL_PATH/logs"

    echo -e "${GREEN}  Plist creato: $LAUNCHD_PLIST${NC}"

    # Carica il servizio
    echo -e "${YELLOW}Avvio servizio...${NC}"
    launchctl load "$LAUNCHD_PLIST"
    sleep 3

    # Verifica che sia in esecuzione
    if pgrep -f "CashProxy" > /dev/null; then
        PID=$(pgrep -f "CashProxy" | head -1)
        echo -e "${GREEN}  CashProxy avviato (PID: $PID)${NC}"
    else
        echo -e "${YELLOW}  Avvio in corso... potrebbe richiedere qualche secondo${NC}"
    fi
fi

echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}  INSTALLAZIONE COMPLETATA!${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
echo -e "CashProxy v${VERSION} installato in: ${GREEN}$INSTALL_PATH${NC}"
echo ""
echo -e "${BLUE}Accesso:${NC}"
echo "  Pannello Admin: http://localhost:5000/admin"
echo "  Setup:          http://localhost:5000/setup"
echo "  HTTPS:          https://localhost:5001/admin"
echo ""
echo -e "${BLUE}Comandi utili:${NC}"
echo "  Avvia:    launchctl load $LAUNCHD_PLIST"
echo "  Ferma:    launchctl unload $LAUNCHD_PLIST"
echo "  Stato:    launchctl list | grep cashproxy"
echo "  Log:      tail -f $INSTALL_PATH/logs/stdout.log"
echo ""
echo -e "${BLUE}Disinstalla:${NC}"
echo "  $0 --uninstall"
echo ""

# Apri browser
if command -v open &> /dev/null; then
    echo -e "${YELLOW}Apertura browser...${NC}"
    sleep 2
    open "http://localhost:5000/admin"
fi
