#!/bin/bash
# build.sh - Compila e instala el Radio Player
# Ejecutar en el sistema destino (Linux con GTK4 y GStreamer)

set -e

echo "========================================"
echo "  G Radio Player - Script de compilación"
echo "========================================"

# ── Verificar Rust ──
if ! command -v cargo &>/dev/null; then
    echo "[!] Rust no encontrado. Instalando via rustup..."
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
    source "$HOME/.cargo/env"
fi

echo "[✓] Rust: $(rustc --version)"

# ── Dependencias del sistema (Ubuntu/Debian) ──
echo ""
echo "[*] Instalando dependencias del sistema..."
sudo apt-get update -q
sudo apt-get install -y \
    pkg-config \
    libgtk-4-dev \
    libgstreamer1.0-dev \
    libgstreamer-plugins-base1.0-dev \
    libgstreamer-plugins-bad1.0-dev \
    gstreamer1.0-plugins-good \
    gstreamer1.0-plugins-bad \
    gstreamer1.0-plugins-ugly \
    gstreamer1.0-libav \
    gstreamer1.0-alsa \
    gstreamer1.0-pulseaudio \
    libssl-dev \
    build-essential

echo "[✓] Dependencias instaladas"

# ── Crear directorios de datos si no existen ──
echo ""
echo "[*] Creando estructura de directorios..."
mkdir -p "$HOME/.gradio/data/tmp"
mkdir -p "$HOME/G Radio/inicio-espacio-pub"
mkdir -p "$HOME/G Radio/fin-espacio-pub"
mkdir -p "$HOME/G Radio/comerciales"

# Crear archivos de configuración por defecto si no existen
[ -f "$HOME/.gradio/data/tmp/upvol" ]   || echo "80" > "$HOME/.gradio/data/tmp/upvol"
[ -f "$HOME/.gradio/data/tmp/downvol" ] || echo "20" > "$HOME/.gradio/data/tmp/downvol"
[ -f "$HOME/.gradio/data/mix" ]          || echo "3" > "$HOME/.gradio/data/mix"
[ -f "$HOME/.gradio/data/tmp/playlist4" ] || touch "$HOME/.gradio/data/tmp/playlist4"
[ -f "$HOME/.gradio/data/tmp/comercialeslist4" ] || touch "$HOME/.gradio/data/tmp/comercialeslist4"

echo "[✓] Directorios y archivos de configuración listos"

# ── Compilar ──
echo ""
echo "[*] Compilando en modo release..."
cd "$(dirname "$0")"
cargo build --release 2>&1

echo ""
echo "[✓] Compilación exitosa: target/release/radio-player"

# ── Instalar (opcional) ──
read -p "[?] ¿Instalar en /usr/local/bin/radio-player? [s/N] " resp
if [[ "$resp" =~ ^[sS]$ ]]; then
    sudo cp target/release/radio-player /usr/local/bin/radio-player
    sudo chmod +x /usr/local/bin/radio-player
    echo "[✓] Instalado en /usr/local/bin/radio-player"
fi

echo ""
echo "========================================"
echo "  Para ejecutar: ./target/release/radio-player"
echo "  O si instalaste: radio-player"
echo "========================================"
