#!/bin/bash
#
# install.sh - Installer automatico per MyHEM
#
# Uso: sudo ./install.sh /percorso/al/pacchetto.zip
#      sudo ./install.sh /percorso/al/pacchetto.tar.gz
#

set -e

INSTALL_DIR="/var/www/MyHEM"
HTPASSWD_FILE="$INSTALL_DIR/config/.htpasswd"

# La cartella in cui si trova lo script è considerata la radice del web
# server dove l'utente ha caricato il pacchetto (.zip o .tar) di MyHEM.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# =====================================================
# FUNZIONE: istruzioni manuali per .htpasswd
# =====================================================
istruzioni_manuali_htpasswd() {
    echo ""
    echo "============================================================"
    echo "  Creazione automatica di .htpasswd non riuscita."
    echo "  Procedura manuale:"
    echo ""
    echo "  1. Installa apache2-utils (se non già presente):"
    echo "       sudo apt-get update && sudo apt-get install -y apache2-utils"
    echo ""
    echo "  2. Crea il file con un primo utente:"
    echo "       sudo htpasswd -c $HTPASSWD_FILE nomeutente"
    echo ""
    echo "  3. Ti verrà chiesto di digitare e confermare la password."
    echo ""
    echo "  4. Verifica che il file appartenga a www-data:"
    echo "       sudo chown www-data:www-data $HTPASSWD_FILE"
    echo "       sudo chmod 640 $HTPASSWD_FILE"
    echo "============================================================"
    echo ""
}

# =====================================================
# 1. Verifica di essere root
# =====================================================
if [ "$EUID" -ne 0 ]; then
    echo "============================================================"
    echo "  Questo script deve essere eseguito con i permessi di root."
    echo "  Riprova digitando:"
    echo ""
    echo "      sudo bash install.sh"
    echo "============================================================"
    exit 1
fi

# =====================================================
# 2. Verifica sistema operativo: deve essere Linux
# =====================================================
if [ "$(uname -s)" != "Linux" ]; then
    echo "============================================================"
    echo "  Questo installer automatico funziona solo su sistemi Linux."
    echo "  Procedura manuale:"
    echo ""
    echo "  1. Estrai il pacchetto (zip/tar) in $INSTALL_DIR"
    echo "  2. Assicurati che file e cartelle siano leggibili dal server web"
    echo "  3. Crea manualmente il file $HTPASSWD_FILE con un tool"
    echo "     compatibile con Apache/Nginx htpasswd (es. tramite un utility"
    echo "     online affidabile o un altro sistema Linux/Mac con apache2-utils)"
    echo "============================================================"
    exit 1
fi

echo "Sistema Linux rilevato, procedo..."

# =====================================================
# 3. Verifica se un'installazione esiste già
# =====================================================
if [ -f "$HTPASSWD_FILE" ]; then
    echo "Installazione già presente ($HTPASSWD_FILE trovato)."
    echo "Uscita senza modifiche."
    exit 0
fi

# =====================================================
# 4. Individuazione automatica dell'archivio
# =====================================================
# Si presume che nella cartella dello script sia presente un solo
# archivio (.zip, .tar, .tar.gz o .tgz) con i file del programma.
mapfile -t ARCHIVES < <(find "$SCRIPT_DIR" -maxdepth 1 -type f \( -iname "*.zip" -o -iname "*.tar" -o -iname "*.tar.gz" -o -iname "*.tgz" \))

if [ ${#ARCHIVES[@]} -eq 0 ]; then
    echo "============================================================"
    echo "  Nessun pacchetto (.zip / .tar / .tar.gz) trovato nella"
    echo "  cartella $SCRIPT_DIR"
    echo "  Carica il pacchetto di MyHEM in questa cartella e riprova."
    echo "============================================================"
    exit 1
fi

if [ ${#ARCHIVES[@]} -gt 1 ]; then
    echo "============================================================"
    echo "  Sono stati trovati più pacchetti nella cartella $SCRIPT_DIR:"
    printf '    - %s\n' "${ARCHIVES[@]}"
    echo ""
    echo "  Lascia un solo file .zip/.tar in questa cartella e riprova,"
    echo "  per evitare di installare per errore la versione sbagliata."
    echo "============================================================"
    exit 1
fi

ARCHIVE="${ARCHIVES[0]}"
echo "Pacchetto trovato: $ARCHIVE"

# =====================================================
# 5. Scompattazione dei file
# =====================================================
echo "Creo la cartella di destinazione $INSTALL_DIR ..."
mkdir -p "$INSTALL_DIR"

echo "Scompatto $ARCHIVE in $INSTALL_DIR ..."
case "$ARCHIVE" in
    *.zip)
        if ! command -v unzip >/dev/null 2>&1; then
            echo "Il comando 'unzip' non è installato. Installazione in corso..."
            apt-get update && apt-get install -y unzip
        fi
        unzip -o "$ARCHIVE" -d "$INSTALL_DIR"
        ;;
    *.tar.gz|*.tgz)
        tar -xzf "$ARCHIVE" -C "$INSTALL_DIR"
        ;;
    *.tar)
        tar -xf "$ARCHIVE" -C "$INSTALL_DIR"
        ;;
    *)
        echo "Formato archivio non riconosciuto (usa .zip, .tar o .tar.gz)."
        exit 1
        ;;
esac

# =====================================================
# 6. Permessi di file e cartelle
# =====================================================
echo "Imposto i permessi..."
find "$INSTALL_DIR" -type d -exec chmod 755 {} \;
find "$INSTALL_DIR" -type f -exec chmod 644 {} \;

# La cartella data/ deve essere scrivibile dal server web
if [ -d "$INSTALL_DIR/data" ]; then
    chmod 775 "$INSTALL_DIR/data"
fi

# Rende eseguibili eventuali script di shell inclusi nel pacchetto
# (es. script di manutenzione, cron job, ecc.)
find "$INSTALL_DIR" -type f -name "*.sh" -exec chmod +x {} \;

# =====================================================
# 7. Proprietario e gruppo
# =====================================================
echo "Imposto proprietario e gruppo (www-data:www-data)..."
chown -R www-data:www-data "$INSTALL_DIR"

# =====================================================
# 8. Creazione .htpasswd tramite finestra utente/password
# =====================================================
mkdir -p "$INSTALL_DIR/config"

HTPASSWD_OK=false

if command -v whiptail >/dev/null 2>&1; then

    if ! command -v htpasswd >/dev/null 2>&1; then
        echo "htpasswd non trovato, installo apache2-utils..."
        apt-get update && apt-get install -y apache2-utils || true
    fi

    if command -v htpasswd >/dev/null 2>&1; then

        USERNAME=$(whiptail --inputbox "Inserisci il nome utente per l'accesso a MyHEM:" 10 60 3>&1 1>&2 2>&3)

        if [ -n "$USERNAME" ]; then
            PASSWORD=$(whiptail --passwordbox "Inserisci la password per $USERNAME:" 10 60 3>&1 1>&2 2>&3)
            PASSWORD_CONFIRM=$(whiptail --passwordbox "Conferma la password:" 10 60 3>&1 1>&2 2>&3)

            if [ "$PASSWORD" == "$PASSWORD_CONFIRM" ] && [ -n "$PASSWORD" ]; then
                if htpasswd -cb "$HTPASSWD_FILE" "$USERNAME" "$PASSWORD"; then
                    chown www-data:www-data "$HTPASSWD_FILE"
                    chmod 640 "$HTPASSWD_FILE"
                    HTPASSWD_OK=true
                    whiptail --msgbox "Utente creato correttamente." 8 50
                fi
            else
                whiptail --msgbox "Le password non coincidono o sono vuote. Creazione annullata." 8 60
            fi
        fi
    fi
else
    echo "whiptail non disponibile, provo con prompt da terminale..."

    if ! command -v htpasswd >/dev/null 2>&1; then
        apt-get update && apt-get install -y apache2-utils || true
    fi

    if command -v htpasswd >/dev/null 2>&1; then
        read -rp "Inserisci il nome utente per l'accesso a MyHEM: " USERNAME
        if [ -n "$USERNAME" ]; then
            if htpasswd -c "$HTPASSWD_FILE" "$USERNAME"; then
                chown www-data:www-data "$HTPASSWD_FILE"
                chmod 640 "$HTPASSWD_FILE"
                HTPASSWD_OK=true
            fi
        fi
    fi
fi

if [ "$HTPASSWD_OK" = false ]; then
    istruzioni_manuali_htpasswd
else
    IP_SERVER=$(hostname -I 2>/dev/null | awk '{print $1}')

    echo ""
    echo "============================================================"
    echo "  Installazione completata con successo!"
    echo ""
    echo "  Utente creato: $USERNAME"
    echo ""
    if [ -n "$IP_SERVER" ]; then
        echo "  Puoi accedere a MyHEM da un browser all'indirizzo:"
        echo "      http://$IP_SERVER/MyHEM/"
    else
        echo "  Non è stato possibile rilevare l'indirizzo IP del server."
        echo "  Puoi trovarlo con il comando: hostname -I"
        echo "  e poi aprire un browser su http://<indirizzo-rilevato>/MyHEM/"
    fi
    echo "============================================================"
fi