#!/bin/zsh

# Tralegraffe Floppy Verifier - Amiga DD 880KB
# Versione 26.04 — Copyright (c) 2026 Tralegraffe Software Solution
# Licenza MIT — Tutti i diritti riservati
# Richiede Greaseweazle — macOS

setopt pipefail

# Directory per i log
LOGDIR="$HOME/greaseweazle_amiga_logs"
GW_BIN="${GW_BIN:-$HOME/Library/Python/3.9/bin/gw}"
AMIGA_FORMAT="amiga.amigados"
AMIGA_IMAGE_SIZE=901120

if [[ ! -x "$GW_BIN" ]]; then
    echo "Errore: Greaseweazle non trovato in: $GW_BIN"
    echo "Imposta GW_BIN con il percorso corretto e rilancia lo script."
    exit 1
fi

# ======================================================================
# ---- SISTEMA DI LICENZE ----
# ======================================================================
LICENSE_API="https://tralegraffe.it/license_api.php"
PRODUCT_CODE="FLOPPY880-MACOS"
APP_VERSION="26.04"
PLATFORM="macos"
LICENSE_FILE="$HOME/.floppy880_license"

get_device_id() {
    local serial
    serial=$(ioreg -l | grep IOPlatformSerialNumber | sed 's/.*= "//;s/"//')
    echo "MAC-${serial:-UNKNOWN}"
}

DEVICE_ID=$(get_device_id)

save_license_key() { echo "$1" > "$LICENSE_FILE" && chmod 600 "$LICENSE_FILE"; }
load_license_key() { [[ -f "$LICENSE_FILE" ]] && cat "$LICENSE_FILE"; }

license_api_call() {
    curl -s -m 15 -X POST -H "Content-Type: application/json" -d "$1" "$LICENSE_API" 2>/dev/null
}

validate_license() {
    local key="$1"
    local response
    response=$(license_api_call "{\"action\":\"validate\",\"product_code\":\"$PRODUCT_CODE\",\"license_key\":\"$key\",\"device_id\":\"$DEVICE_ID\",\"app_version\":\"$APP_VERSION\",\"platform\":\"$PLATFORM\"}")
    if [[ -z "$response" ]]; then
        echo "⚠️  Impossibile contattare il server licenze. Riprova più tardi."
        exit 1
    fi
    local valid code message
    valid=$(echo "$response" | grep -o '"valid" *: *[a-z]*' | head -1 | grep -o 'true\|false')
    code=$(echo "$response" | grep -o '"code" *: *"[^"]*"' | head -1 | sed 's/.*: *"//;s/"//')
    message=$(echo "$response" | grep -o '"message" *: *"[^"]*"' | head -1 | sed 's/.*: *"//;s/"//')
    if [[ "$valid" == "true" ]]; then
        echo "✅ Software attivato. Licenza lifetime valida."
        return 0
    else
        case "$code" in
            invalid_key) echo "❌ Chiave licenza non valida."; rm -f "$LICENSE_FILE" ;;
            suspended) echo "❌ Licenza sospesa. Contatta il supporto." ;;
            revoked) echo "❌ Licenza revocata. Contatta il supporto." ;;
            activation_limit_reached) echo "❌ Limite dispositivi raggiunto. Contatta il supporto." ;;
            *) echo "❌ Errore licenza: $message" ;;
        esac
        return 1
    fi
}

request_activation() {
    local name="$1" email="$2"
    local response
    response=$(license_api_call "{\"action\":\"request_trial\",\"product_code\":\"$PRODUCT_CODE\",\"device_id\":\"$DEVICE_ID\",\"app_version\":\"$APP_VERSION\",\"platform\":\"$PLATFORM\",\"customer_name\":\"$name\",\"customer_email\":\"$email\"}")
    if [[ -z "$response" ]]; then
        echo "❌ Impossibile contattare il server licenze."
        return 1
    fi
    local valid code issued_key message
    valid=$(echo "$response" | grep -o '"valid" *: *[a-z]*' | head -1 | grep -o 'true\|false')
    code=$(echo "$response" | grep -o '"code" *: *"[^"]*"' | head -1 | sed 's/.*: *"//;s/"//')
    issued_key=$(echo "$response" | grep -o '"issued_license_key" *: *"[^"]*"' | head -1 | sed 's/.*: *"//;s/"//')
    message=$(echo "$response" | grep -o '"message" *: *"[^"]*"' | head -1 | sed 's/.*: *"//;s/"//')
    if [[ "$valid" == "true" && -n "$issued_key" ]]; then
        save_license_key "$issued_key"
        echo "✅ Software attivato con successo! Licenza lifetime."
        return 0
    elif [[ "$code" == "trial_active" && -n "$issued_key" ]]; then
        save_license_key "$issued_key"
        echo "✅ Software già attivato su questo dispositivo."
        return 0
    else
        echo "❌ Attivazione non riuscita: $message"
        return 1
    fi
}

check_license() {
    echo "\n🔑 Verifica attivazione..."
    local saved_key
    saved_key=$(load_license_key)
    if [[ -n "$saved_key" ]]; then
        if validate_license "$saved_key"; then return 0; fi
        saved_key=$(load_license_key)
    fi
    if [[ -z "$saved_key" ]]; then
        echo ""
        echo "⚠️  Questo software richiede un'attivazione gratuita (una tantum)."
        echo "⚠️  È necessaria una connessione internet."
        echo ""
        read -r "act_name?Nome e Cognome: "
        read -r "act_email?Email: "
        if [[ -z "$act_name" || -z "$act_email" ]]; then
            echo "❌ Nome e email sono obbligatori per l'attivazione."
            exit 1
        fi
        if request_activation "$act_name" "$act_email"; then return 0; else exit 1; fi
    fi
}

check_license
# ======================================================================
# ---- FINE SISTEMA DI LICENZE ----
# ======================================================================

typeset -r RESET=$'\033[0m'
typeset -r BOLD=$'\033[1m'
typeset -r CYAN=$'\033[36m'
typeset -r GREEN=$'\033[32m'
typeset -r YELLOW=$'\033[33m'
typeset -r RED=$'\033[31m'
typeset -r TOTAL_STEPS=5

format_duration() {
    local total_seconds="$1"
    local hours minutes seconds

    if [[ "$total_seconds" -lt 0 ]]; then
        total_seconds=0
    fi

    hours=$((total_seconds / 3600))
    minutes=$(((total_seconds % 3600) / 60))
    seconds=$((total_seconds % 60))

    if [[ "$hours" -gt 0 ]]; then
        printf '%02d:%02d:%02d' "$hours" "$minutes" "$seconds"
    else
        printf '%02d:%02d' "$minutes" "$seconds"
    fi
}

progress_bar() {
    local current="$1"
    local total="$2"
    local start_ts="$3"
    local label="$4"
    local width=30
    local percent filled empty bar spaces now elapsed eta

    if [[ "$total" -le 0 ]]; then
        printf '\r%s' "$label"
        return
    fi

    now=$(date +%s)
    elapsed=$((now - start_ts))

    if [[ "$current" -gt 0 ]]; then
        eta=$((elapsed * (total - current) / current))
    else
        eta=0
    fi

    percent=$((current * 100 / total))
    filled=$((current * width / total))
    empty=$((width - filled))

    printf -v bar '%*s' "$filled" ''
    bar=${bar// /█}
    printf -v spaces '%*s' "$empty" ''
    spaces=${spaces// /░}

    printf '\r%s[%s%s]%s %3d%% (%d/%d) %s | trascorso %s | residuo %s' \
        "$CYAN" "$bar" "$spaces" "$RESET" "$percent" "$current" "$total" "$label" \
        "$(format_duration "$elapsed")" "$(format_duration "$eta")"
}

print_banner() {
    echo "${CYAN}${BOLD}╔════════════════════════════════════════════╗${RESET}"
    echo "${CYAN}${BOLD}║        Tralegraffe Software Solution       ║${RESET}"
    echo "${CYAN}${BOLD}║     Greaseweazle • Formattazione Amiga     ║${RESET}"
    echo "${CYAN}${BOLD}║           Formato: Amiga DD (880 KB)       ║${RESET}"
    echo "${CYAN}${BOLD}╚════════════════════════════════════════════╝${RESET}"
    echo
}

run_step() {
    local step_number="$1"
    local total_steps="$2"
    local label="$3"
    shift 3

    echo "${CYAN}>>> ${label}...${RESET}"
    if "$@" 2>&1 | tee -a "$LOG"; then
        progress_bar "$step_number" "$total_steps" "$JOB_START" "$label"
        echo
        return 0
    fi

    progress_bar $((step_number - 1)) "$total_steps" "$JOB_START" "ERRORE: $label"
    echo
    return 1
}

print_result() {
    local log_file="$1"
    local reason="$2"

    if [[ -n "$reason" ]]; then
        echo "${RED}${BOLD}❌ VERIFICA FALLITA${RESET} - $reason - vedi log: $log_file"
    else
        echo "${GREEN}${BOLD}✅ FLOPPY OK${RESET} - vedi log: $log_file"
    fi
}

mkdir -p "$LOGDIR"

print_banner

while true; do
    echo "${YELLOW}Inserisci un floppy e premi INVIO${RESET} (oppure digita q per uscire)"
    read -r input
    if [[ "$input" == "q" ]]; then
        echo "Uscita."
        exit 0
    fi

    TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
    IMG="$LOGDIR/amiga_$TIMESTAMP.adf"
    LOG="$LOGDIR/amiga_$TIMESTAMP.log"
    BLANK_IMG=$(mktemp "$LOGDIR/amiga_blank_XXXXXX.adf")
    JOB_START=$(date +%s)

    truncate -s "$AMIGA_IMAGE_SIZE" "$BLANK_IMG"
    : > "$LOG"

    FAILURE_REASON=""

    progress_bar 0 "$TOTAL_STEPS" "$JOB_START" "Avvio verifica floppy"
    echo

    if ! run_step 1 "$TOTAL_STEPS" "Verifica dispositivo" "$GW_BIN" info; then
        FAILURE_REASON="Greaseweazle non disponibile o dispositivo non risponde"
        print_result "$LOG" "$FAILURE_REASON"
        echo
        cleanup
        continue
    fi

    if ! run_step 2 "$TOTAL_STEPS" "Cancellazione tracce" "$GW_BIN" erase; then
        FAILURE_REASON="errore durante la cancellazione delle tracce"
        print_result "$LOG" "$FAILURE_REASON"
        echo
        cleanup
        continue
    fi

    if ! run_step 3 "$TOTAL_STEPS" "Scrittura formato Amiga DD" "$GW_BIN" write --format="$AMIGA_FORMAT" --pre-erase "$BLANK_IMG"; then
        FAILURE_REASON="errore durante la scrittura o la verifica del floppy"
        print_result "$LOG" "$FAILURE_REASON"
        echo
        cleanup
        continue
    fi

    if ! run_step 4 "$TOTAL_STEPS" "Lettura immagine" "$GW_BIN" read --format="$AMIGA_FORMAT" "$IMG"; then
        FAILURE_REASON="errore durante la lettura del floppy"
        print_result "$LOG" "$FAILURE_REASON"
        echo
        cleanup
        continue
    fi

    if ! cmp -s "$BLANK_IMG" "$IMG"; then
        FAILURE_REASON="l'immagine letta non coincide con il disco scritto"
    fi

    progress_bar 5 "$TOTAL_STEPS" "$JOB_START" "Confronto finale"
    echo

    echo ""
    echo "${BOLD}>>> RISULTATO FLOPPY:${RESET}"
    print_result "$LOG" "$FAILURE_REASON"

    echo ""
    cleanup
done
