#!/bin/bash
# instalar.sh — Instala G Radio Player parcheando el prerm roto de versiones anteriores
set -e
cd "$(dirname "$0")"

ARCH="$(dpkg --print-architecture 2>/dev/null || uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')"
DEB=""

# Detectar el .deb para esta arquitectura
for candidate in \
    "gradio-player_"*"_${ARCH}.deb" \
    "gradio-player_"*"_${ARCH}_bookworm.deb"; do
    # shellcheck disable=SC2144
    if ls $candidate 2>/dev/null | head -1 | grep -q .; then
        DEB="$(ls $candidate 2>/dev/null | sort -V | tail -1)"
        break
    fi
done

if [ -z "$DEB" ]; then
    echo "ERROR: No se encontró ningún .deb para arquitectura '$ARCH' en el directorio actual."
    echo "       Ejecuta este script desde la carpeta que contiene el .deb."
    exit 1
fi

echo "==> Instalando: $DEB"

# Parchear prerm y postrm instalados si tienen bugs históricos
PRERM="/var/lib/dpkg/info/gradio-player.prerm"
POSTRM="/var/lib/dpkg/info/gradio-player.postrm"

if [ -f "$PRERM" ] && grep -q "pkill" "$PRERM"; then
    echo "==> Parcheando prerm instalado (contiene pkill — bug conocido)..."
    printf '#!/bin/bash\nexit 0\n' | sudo tee "$PRERM" > /dev/null
fi

if [ -f "$POSTRM" ] && ! grep -q 'case "\$1"' "$POSTRM"; then
    echo "==> Parcheando postrm instalado (borra archivos en upgrade — bug conocido)..."
    sudo tee "$POSTRM" > /dev/null << 'POSTRM_FIX'
#!/bin/bash
case "$1" in
    remove|purge)
        for BIN in radio-player comercial-scheduler playlist-refill \
                   gradio.sh gr-buscador gr-playlist gr-pautaje gr-parrilla \
                   gr-botonera gr-visor gr-reportes gr-record; do
            rm -f "/usr/local/bin/$BIN"
        done
        rm -rf /usr/local/share/radio-player
        rm -f /usr/share/applications/com.gradio.radio-player.desktop
        rm -f /usr/share/applications/gradio-player.desktop
        rm -f /usr/share/icons/hicolor/48x48/apps/gradio-player.png
        command -v gtk-update-icon-cache &>/dev/null && gtk-update-icon-cache -f -t /usr/share/icons/hicolor 2>/dev/null || true
        command -v update-desktop-database &>/dev/null && update-desktop-database /usr/share/applications 2>/dev/null || true
        ;;
esac
POSTRM_FIX
    sudo chmod 755 "$POSTRM"
fi

sudo dpkg -i "$DEB"

echo ""
echo "✅  Instalación completa. Ejecutar: gradio.sh"
