#!/bin/bash
# ─── G Radio Player — instalador para Arch Linux ─────────────────────────────
set -e
cd "$(dirname "$0")"

INSTALL_DIR="$HOME/.local/share/radio-player"
BIN_DIR="$HOME/.local/bin"
DESKTOP_DIR="$HOME/.local/share/applications"

# ── 1. Dependencias del sistema (pacman) ──────────────────────────────────────
echo "==> Verificando dependencias..."

PKGS=(
    gstreamer
    gst-plugins-base
    gst-plugins-good
    gst-plugins-bad
    gst-plugins-ugly
    gst-libav
    ffmpeg
)

MISSING=()
for pkg in "${PKGS[@]}"; do
    if ! pacman -Q "$pkg" &>/dev/null; then
        MISSING+=("$pkg")
    fi
done

if [ ${#MISSING[@]} -gt 0 ]; then
    echo "  Faltan paquetes: ${MISSING[*]}"
    echo "  Instalando con pacman..."
    sudo pacman -S --needed --noconfirm "${MISSING[@]}"
fi

# ── 2. Instalar binarios ──────────────────────────────────────────────────────
echo "==> Instalando binarios en $BIN_DIR..."
BINS=(
    radio-player
    comercial-scheduler
    playlist-refill
    gr-visor
    gr-botonera
    gr-buscador
    gr-parrilla
    gr-pautaje
    gr-playlist
    gr-record
    gr-reportes
)
for bin in "${BINS[@]}"; do
    if [ ! -f "target/release/$bin" ]; then
        echo "ERROR: binario no encontrado: target/release/$bin"
        echo "       Compila el proyecto antes de instalar (cargo build --release)"
        exit 1
    fi
done
mkdir -p "$BIN_DIR"
for bin in "${BINS[@]}"; do
    cp "target/release/$bin" "$BIN_DIR/$bin"
    chmod +x "$BIN_DIR/$bin"
done

# ── 3. Instalar assets ────────────────────────────────────────────────────────
echo "==> Instalando assets..."
if [ ! -d "target/data/panel/Time" ]; then
    echo "ERROR: carpeta 'target/data/panel/Time' no encontrada en el paquete"
    exit 1
fi
mkdir -p "$HOME/.gradio/data/panel"
cp -r target/data/panel/Time "$HOME/.gradio/data/panel/Time"

# ── 4. Crear lanzador principal ───────────────────────────────────────────────
echo "==> Creando lanzador..."
mkdir -p "$INSTALL_DIR"
cat > "$INSTALL_DIR/gradio.sh" << 'LAUNCHER'
#!/bin/bash
BIN="$HOME/.local/bin"

mkdir -p "$HOME/.gradio/data/tmp"
mkdir -p "$HOME/.gradio/data/parrilla"
mkdir -p "$HOME/.gradio/data/comerciales"
mkdir -p "$HOME/.gradio/data/eventos-espera"
mkdir -p "$HOME/.gradio/data/eventos"
mkdir -p "$HOME/.gradio/data/reporte"
mkdir -p "$HOME/G Radio/inicio-espacio-pub"
mkdir -p "$HOME/G Radio/fin-espacio-pub"

"$BIN/comercial-scheduler" &
SCHED_PID=$!
"$BIN/playlist-refill" &
REFILL_PID=$!

"$BIN/radio-player" "$@"
EXIT_CODE=$?

kill $SCHED_PID $REFILL_PID 2>/dev/null
wait $SCHED_PID $REFILL_PID 2>/dev/null
exit $EXIT_CODE
LAUNCHER
chmod +x "$INSTALL_DIR/gradio.sh"
ln -sf "$INSTALL_DIR/gradio.sh" "$BIN_DIR/gradio"

# ── 5. Entrada de menú de escritorio ──────────────────────────────────────────
echo "==> Registrando en el menú de aplicaciones..."
mkdir -p "$DESKTOP_DIR"
# Limpiar entrada de versiones antiguas (nombre no coincidía con el app_id)
rm -f "$DESKTOP_DIR/gradio-player.desktop"
cat > "$DESKTOP_DIR/com.gradio.radio-player.desktop" << DESKTOP
[Desktop Entry]
Type=Application
Name=G Radio Player
GenericName=Radio Player
Comment=Reproductor de radio profesional
Exec=$INSTALL_DIR/gradio.sh
Icon=gradio-player
Categories=AudioVideo;Audio;Player;
Terminal=false
StartupNotify=true
DESKTOP

update-desktop-database "$DESKTOP_DIR" 2>/dev/null || true

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

echo ""
echo "  Instalación completa."
echo ""
echo "  Ejecutar:  gradio"
echo "  Desinstalar:  ./uninstall.sh"
