#!/bin/bash
# GR Processor — instalador
set -e
cd "$(dirname "$0")"

BIN_DIR="$HOME/.local/bin"
DESKTOP_DIR="$HOME/.local/share/applications"
ICON_DIR="$HOME/.local/share/icons/hicolor/256x256/apps"

# ── 1. Verificar dependencias ─────────────────────────────────────────────────
echo "==> Verificando dependencias..."

if command -v apt &>/dev/null; then
    # En Debian 13+ (Trixie) libasound se renombró con sufijo t64
    DEB_VER=$(. /etc/os-release 2>/dev/null && echo "${VERSION_ID:-0}")
    if [ "${DEB_VER:-0}" -ge 13 ] 2>/dev/null; then
        ASOUND_PKG="libasound2t64"
    else
        ASOUND_PKG="libasound2"
    fi

    PKGS=(libgtk-4-1 "$ASOUND_PKG")
    MISSING=()
    for pkg in "${PKGS[@]}"; do
        dpkg -l "$pkg" 2>/dev/null | grep -q "^ii" || MISSING+=("$pkg")
    done
    if [ ${#MISSING[@]} -gt 0 ]; then
        echo "  Faltan: ${MISSING[*]}"
        echo "  Instalando dependencias..."
        if command -v sudo &>/dev/null; then
            sudo apt-get install -y "${MISSING[@]}"
        else
            apt-get install -y "${MISSING[@]}" || {
                echo "[!] Sin privilegios para instalar. Ejecuta:"
                echo "    sudo apt install ${MISSING[*]}"
                exit 1
            }
        fi
    else
        echo "  Dependencias OK."
    fi

elif command -v dnf &>/dev/null; then
    PKGS=(gtk4 alsa-lib)
    MISSING=()
    for pkg in "${PKGS[@]}"; do
        rpm -q "$pkg" &>/dev/null || MISSING+=("$pkg")
    done
    if [ ${#MISSING[@]} -gt 0 ]; then
        echo "  Instalando: ${MISSING[*]}"
        sudo dnf install -y "${MISSING[@]}"
    else
        echo "  Dependencias OK."
    fi

else
    echo "  [!] Gestor de paquetes no reconocido."
    echo "      Asegúrate de tener GTK4 (libgtk-4-1) y ALSA (libasound2) instalados."
fi

# ── 2. Localizar binario ──────────────────────────────────────────────────────
if [ -f "./gr-processor" ]; then
    BINARY="./gr-processor"
elif [ -f "target/release/gr-processor" ]; then
    BINARY="target/release/gr-processor"
else
    echo ""
    echo "[!] Binario no encontrado."
    echo "    Desde el ZIP: ejecuta install.sh dentro de la carpeta extraída."
    echo "    Desde fuente: cargo build --release"
    exit 1
fi

# ── 3. Verificar compatibilidad de arquitectura ───────────────────────────────
ELF_INTERP=$(readelf -l "$BINARY" 2>/dev/null | grep "interpreter" | grep -oE '/[^ ]+' | tr -d ']')
if [ -n "$ELF_INTERP" ] && [ ! -f "$ELF_INTERP" ]; then
    echo ""
    echo "[!] Binario incompatible con este sistema ($(uname -m))."
    echo "    Intérprete requerido: $ELF_INTERP — no encontrado."
    echo "    Usa el ZIP para la arquitectura correcta."
    echo ""
    exit 1
fi

# ── 4. Instalar binario ───────────────────────────────────────────────────────
echo "==> Instalando gr-processor en $BIN_DIR..."
mkdir -p "$BIN_DIR"
cp "$BINARY" "$BIN_DIR/gr-processor"
chmod +x "$BIN_DIR/gr-processor"

# ── 5. Instalar ícono ─────────────────────────────────────────────────────────
mkdir -p "$ICON_DIR"
if [ -f "./assets/gradio.png" ]; then
    cp "./assets/gradio.png" "$ICON_DIR/gr-processor.png"
elif [ -f "./gr-processor.png" ]; then
    cp "./gr-processor.png" "$ICON_DIR/gr-processor.png"
fi
gtk-update-icon-cache "$HOME/.local/share/icons/hicolor" 2>/dev/null || true

# ── 6. Entrada de menú de escritorio ─────────────────────────────────────────
echo "==> Registrando en el menú de aplicaciones..."
mkdir -p "$DESKTOP_DIR"
cat > "$DESKTOP_DIR/gr-processor.desktop" << DESKTOP
[Desktop Entry]
Type=Application
Name=GR Processor
GenericName=Audio Processor
Comment=Procesador de audio multiband para radiodifusión FM
Exec=gr-processor
Icon=gr-processor
Categories=AudioVideo;Audio;
Terminal=false
StartupNotify=true
Keywords=radio;audio;processor;multiband;fm;broadcast;
DESKTOP
update-desktop-database "$DESKTOP_DIR" 2>/dev/null || true

# ── 7. Advertencia de PATH ────────────────────────────────────────────────────
if [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
    echo ""
    echo "  AVISO: $HOME/.local/bin no está en tu PATH."
    echo "  Agrega esta línea a ~/.bashrc o ~/.zshrc:"
    echo ""
    echo '    export PATH="$HOME/.local/bin:$PATH"'
    echo ""
fi

echo ""
echo "OK  GR Processor instalado correctamente."
echo ""
echo "  Ejecutar:       gr-processor"
echo "  Desinstalar:    ./uninstall.sh"
echo ""
