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

set -e

echo "========================================"
echo "  G Radio Player TV - 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 \
    gstreamer1.0-gtk4 \
    v4l-utils \
    libssl-dev \
    build-essential

echo "[✓] Dependencias instaladas"

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

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

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

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