#!/usr/bin/env bash
# install-rpi.sh — Instala Fusion2X Web Operator en Raspberry Pi
# Uso: sudo bash install-rpi.sh

set -euo pipefail

DOWNLOAD_URL="https://lw6emn.ar/software/rpi/fusion2x-web.zip"
INSTALL_DIR="/opt/fusion2x"
BINARY="fusion2x-web"
SERVICE="fusion2x-web"
SERVICE_FILE="/etc/systemd/system/${SERVICE}.service"
RUN_USER="${SUDO_USER:-pi}"

# ── Colores ────────────────────────────────────────────────────────────────────
R='\033[0;31m'; G='\033[0;32m'; Y='\033[1;33m'; C='\033[0;36m'; N='\033[0m'
info()  { echo -e "${C}[INFO]${N}  $*"; }
ok()    { echo -e "${G}[ OK ]${N}  $*"; }
warn()  { echo -e "${Y}[WARN]${N}  $*"; }
error() { echo -e "${R}[ERR ]${N}  $*"; exit 1; }

# ── Verificaciones ─────────────────────────────────────────────────────────────
[[ $EUID -ne 0 ]] && error "Ejecutá con sudo: wget -qO- https://lw6emn.ar/software/fusion2x/install-rpi.sh | sudo bash"

for cmd in wget unzip systemctl; do
    command -v "$cmd" &>/dev/null || error "Falta '$cmd'. Instalalo con: sudo apt install $cmd"
done

# ── Detener servicio existente ─────────────────────────────────────────────────
if systemctl is-active --quiet "$SERVICE" 2>/dev/null; then
    info "Deteniendo servicio existente..."
    systemctl stop "$SERVICE"
fi

# ── Descarga ───────────────────────────────────────────────────────────────────
TMP_ZIP="$(mktemp /tmp/fusion2x-XXXXXX.zip)"
trap 'rm -f "$TMP_ZIP"' EXIT

info "Descargando $DOWNLOAD_URL ..."
wget -q --show-progress -O "$TMP_ZIP" "$DOWNLOAD_URL" || error "No se pudo descargar el zip."
ok "Descarga completa."

# ── Instalación ────────────────────────────────────────────────────────────────
info "Instalando en $INSTALL_DIR ..."
mkdir -p "$INSTALL_DIR"

# Preservar .ini si ya existe
INI_BACKUP=""
if [[ -f "$INSTALL_DIR/fusion2x.ini" ]]; then
    INI_BACKUP="$(mktemp /tmp/fusion2x-ini-XXXXXX)"
    cp "$INSTALL_DIR/fusion2x.ini" "$INI_BACKUP"
    info "Configuración existente preservada."
fi

unzip -qo "$TMP_ZIP" -d "$INSTALL_DIR"
chmod +x "$INSTALL_DIR/$BINARY"
chown -R "$RUN_USER:$RUN_USER" "$INSTALL_DIR"

# Restaurar .ini si había uno previo
if [[ -n "$INI_BACKUP" ]]; then
    cp "$INI_BACKUP" "$INSTALL_DIR/fusion2x.ini"
    rm -f "$INI_BACKUP"
    ok "Configuración restaurada."
fi

# Crear .ini mínimo si no existe
if [[ ! -f "$INSTALL_DIR/fusion2x.ini" ]]; then
    cat > "$INSTALL_DIR/fusion2x.ini" <<'EOF'
[ft5d]
port     =
sysop    =
model    = FT5D

[ysf]
callsign =

[radio]
freq     = 144.000000
offset   = +000.000000
power    = 0

[bm]
server   =
password =

[general]
lang            = es
log_file        = ./log/fusion2x.log
log_maxbytes    = 1000000
log_backupcount = 5

[web]
host     = 0.0.0.0
port     = 8080
username = admin
password = admin
EOF
    chown "$RUN_USER:$RUN_USER" "$INSTALL_DIR/fusion2x.ini"
    warn "Se creó fusion2x.ini con valores por defecto. Editalo antes de iniciar el servicio."
fi

ok "Archivos instalados."

# ── Servicio systemd ───────────────────────────────────────────────────────────
info "Configurando servicio systemd..."

SVC_SRC="$INSTALL_DIR/fusion2x-web.service"
[[ -f "$SVC_SRC" ]] || error "No se encontró $SVC_SRC en el zip."

sed -e "s|__USER__|$RUN_USER|g" \
    -e "s|__INSTALL_DIR__|$INSTALL_DIR|g" \
    "$SVC_SRC" > "$SERVICE_FILE"

systemctl daemon-reload
systemctl enable "$SERVICE"
systemctl start  "$SERVICE"

ok "Servicio '$SERVICE' habilitado e iniciado."

# ── Resumen ────────────────────────────────────────────────────────────────────
echo ""
echo -e "${G}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${N}"
echo -e "${G}  Fusion2X Web Operator instalado correctamente${N}"
echo -e "${G}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${N}"
echo ""

IP=$(hostname -I 2>/dev/null | awk '{print $1}')
WEB_PORT=$(grep -oP '(?<=^port\s=\s)\d+' "$INSTALL_DIR/fusion2x.ini" 2>/dev/null || echo "8080")
echo -e "  Directorio : ${C}$INSTALL_DIR${N}"
echo -e "  Config     : ${C}$INSTALL_DIR/fusion2x.ini${N}"
echo -e "  Interfaz   : ${C}http://${IP:-<ip-raspberry>}:${WEB_PORT}${N}"
echo ""
echo -e "  Comandos útiles:"
echo -e "    sudo systemctl status  $SERVICE"
echo -e "    sudo systemctl restart $SERVICE"
echo -e "    sudo journalctl -u $SERVICE -f"
echo ""
