#!/bin/bash
# Mundo Games Toolbox - funciones comunes.
# Se carga desde menu.sh y descargas.sh (source). No se ejecuta solo.

MG_DIR="${MG_DIR:-/userdata/system/mundogames}"
# La direccion del servidor vive en $MG_DIR/servidor.conf (la crea el instalador o el lanzador)
[ -z "$MG_URL" ] && [ -f "$MG_DIR/servidor.conf" ] && . "$MG_DIR/servidor.conf"
MG_LOG="$MG_DIR/logs/toolbox.log"
MG_BACKUPS="$MG_DIR/backups"
MG_INSTALADOS="$MG_DIR/instalados"
MG_DESCARGAS="$MG_DIR/descargas"
MG_TITULO="${MG_TITULO:-Mundo Games Toolbox}"
MG_MARGEN_KB=$((512 * 1024))    # espacio libre que siempre se deja en /userdata
MG_JUSTO_KB=$((3 * 1024 * 1024))   # si tras instalar quedaria menos libre, se avisa (almacenamiento justo)
# Rutas de la consola (solo se cambian para pruebas fuera de Batocera)
MG_ROMS="${MG_ROMS:-/userdata/roms}"
MG_WINE_CUSTOM="${MG_WINE_CUSTOM:-/userdata/system/wine/custom}"
MG_ES_CFG="${MG_ES_CFG:-/userdata/system/configs/emulationstation}"
MG_BOTELLAS="${MG_BOTELLAS:-/userdata/system/wine-bottles}"
MG_RAIZ="${MG_RAIZ:-/userdata}"
MG_SCRIPTS="${MG_SCRIPTS:-/userdata/system/scripts}"   # hooks gameStart/gameStop de Batocera
# Valores de fabrica de las rutas que una receta puede cambiar solo para su juego (Batocera 38 no
# tiene wine/custom ni wine-bottles). instalar_juego los restablece antes de cargar cada receta.
MG_WINE_CUSTOM_BASE="$MG_WINE_CUSTOM"; MG_BOTELLAS_BASE="$MG_BOTELLAS"

export LANG=en_US.UTF-8 LC_ALL=en_US.UTF-8
[ -f "$MG_DIR/toolbox/dialogrc" ] && export DIALOGRC="$MG_DIR/toolbox/dialogrc"

mkdir -p "$MG_DIR/logs" "$MG_BACKUPS" "$MG_INSTALADOS" "$MG_DESCARGAS"

# ---------------------------------------------------------------- mensajes

log() { echo "$(date '+%F %T') $*" >> "$MG_LOG"; }

msg() {    # msg "Titulo" "Texto" [alto] [ancho]
    dialog --backtitle "$MG_TITULO" --title "$1" --msgbox "\n$2" "${3:-10}" "${4:-60}" 2>&1 >/dev/tty
}

confirmar() {    # confirmar "Titulo" "Texto" [alto] [ancho]  -> 0 = Si
    dialog --backtitle "$MG_TITULO" --title "$1" --yes-label "Si" --no-label "No" \
        --yesno "\n$2" "${3:-10}" "${4:-60}" 2>&1 >/dev/tty
}

info() {    # mensaje sin espera (entre pasos)
    dialog --backtitle "$MG_TITULO" --title "$1" --infobox "\n$2" 7 60 2>&1 >/dev/tty
}

error() {    # error "Texto": registra y avisa. Devuelve 1 para poder usar "|| return"
    log "ERROR $*"
    dialog --backtitle "$MG_TITULO" --title "Error" --msgbox \
        "\n$*\n\nSi el problema continua, saca una foto de esta pantalla y enviala a Mundo Games." 13 64 2>&1 >/dev/tty
    return 1
}

avisar_es() { curl -s -m 3 -X POST --data "$1" http://127.0.0.1:1234/notify >/dev/null 2>&1; }
recargar_juegos() { curl -s -m 10 http://127.0.0.1:1234/reloadgames >/dev/null 2>&1; }

humano_kb() { awk -v k="$1" 'BEGIN{ if (k>=1048576) printf "%.1f GB", k/1048576; else printf "%d MB", k/1024 }'; }

# ---------------------------------------------------------------- sistema

version_batocera() { cut -d' ' -f1 /usr/share/batocera/batocera.version 2>/dev/null; }

# version_coincide VERSION PATRONES -> 0 si VERSION coincide con alguno de los patrones (glob), que se
# separan con "|": "4[013]*", "38*|4[013]*". Es la 4a columna de juegos/catalogo.txt y JUEGO_BATOCERA.
version_coincide() {
    local v="$1" p; local -a pats
    IFS='|' read -r -a pats <<< "$2"
    for p in "${pats[@]}"; do
        case "$v" in $p) return 0 ;; esac
    done
    return 1
}
libre_kb() { df -Pk "$MG_ROMS" | awk 'NR==2 {print $4}'; }

comprobar_arquitectura() {
    [ "$(uname -m)" = "x86_64" ] && return 0
    error "Esta consola ($(uname -m)) no es compatible. La Toolbox es solo para Retro Mini 3 (x86_64)."
}

comprobar_internet() {
    curl -fsS -m 15 --retry 2 --retry-delay 3 -o /dev/null "$MG_URL/toolbox/VERSION" && return 0
    error "No se pudo conectar con el servidor de Mundo Games.\nRevisa que la consola tenga internet."
}

# Lee CLAVE=valor de un archivo sin ejecutarlo.
leer_clave() { sed -n "s/^$2=//p" "$1" | head -n1 | tr -d '\r'; }

# ---------------------------------------------------------------- batocera.conf

BATOCERA_CONF="${BATOCERA_CONF:-/userdata/system/batocera.conf}"
_conf_respaldado=""

respaldar() {    # respaldar /ruta/archivo -> copia con fecha en backups/
    [ -f "$1" ] || return 0
    local destino="$MG_BACKUPS/$(basename "$1").$(date +%Y%m%d-%H%M%S)"
    cp -p "$1" "$destino" && log "Respaldo $1 -> $destino"
}

# ajuste_juego SISTEMA CARPETA CLAVE VALOR
# Fija un ajuste solo para este juego: windows["RE2HD.pc"].clave=valor.
# No toca los ajustes globales ni los de otros juegos. Idempotente.
ajuste_juego() {
    local linea="$1[\"$2\"].$3"
    if [ -z "$_conf_respaldado" ]; then respaldar "$BATOCERA_CONF"; _conf_respaldado=1; fi
    touch "$BATOCERA_CONF"
    awk -v k="$linea" 'index($0, k"=") != 1' "$BATOCERA_CONF" > "$BATOCERA_CONF.mgtmp" \
        && echo "$linea=$4" >> "$BATOCERA_CONF.mgtmp" \
        && mv "$BATOCERA_CONF.mgtmp" "$BATOCERA_CONF"
    log "Ajuste $linea=$4"
}

# ---------------------------------------------------------------- gamelist

# Batocera 40 y la "41cp" no traen xmlstarlet. En esas consolas esta funcion en Python hace lo poco
# que la Toolbox usa de xmlstarlet para editar las listas de juegos (gamelist.xml). Si la consola tiene
# xmlstarlet, se usa el de verdad y esto no se define. Admite solo:
#   ed -L (-d RUTA | -s RUTA -t elem -n NOMBRE -v VALOR)... ARCHIVO
#   sel -t -v "count(RUTA)" ARCHIVO        sel -t -m RUTA (-v CAMPO | -n)... ARCHIVO
# RUTA: /gameList, /gameList/game[last()], /gameList/game[path='X'] (o "X") y
#       /gameList/game[contains(translate(path,'A..Z','a..z'),'x')]
# (Mismo bloque en instalar.sh, "Instalar Mundo Games Toolbox.sh", toolbox/lib.sh y toolbox/sistema.sh:
#  si cambias uno, cambia los otros.)
if ! type -P xmlstarlet >/dev/null; then
xmlstarlet() {
    python3 - "$@" <<'MG_PY'
import os, re, sys, xml.etree.ElementTree as ET

def falla(texto):
    sys.exit("xmlstarlet (Python): " + texto)

def leer(archivo):
    try:
        return ET.parse(archivo, ET.XMLParser(target=ET.TreeBuilder(insert_comments=True)))
    except (ET.ParseError, OSError) as e:
        print("xmlstarlet (Python): %s: %s" % (archivo, e), file=sys.stderr)
        sys.exit(3)     # como xmlstarlet

def nodos(raiz, ruta):
    if ruta == "/gameList":
        return [raiz]
    m = re.fullmatch(r"/gameList/game(?:\[(.*)\])?", ruta)
    if not m:
        falla("ruta no soportada: " + ruta)
    juegos, filtro = raiz.findall("game"), m.group(1)
    if filtro is None:
        return juegos
    if filtro == "last()":
        return juegos[-1:]
    m = re.fullmatch(r"path=(['\"])(.*)\1", filtro)
    if m:
        return [g for g in juegos if (g.findtext("path") or "") == m.group(2)]
    m = re.fullmatch(r"contains\(translate\(path,'[A-Z]+','[a-z]+'\),'([^']*)'\)", filtro)
    if m:
        return [g for g in juegos if m.group(1) in (g.findtext("path") or "").lower()]
    falla("ruta no soportada: " + ruta)

def ed(args):
    if len(args) < 2 or args[0] != "-L":
        falla("solo se admite ed -L")
    archivo, ops, i = args[-1], args[1:-1], 0
    arbol = leer(archivo)
    raiz = arbol.getroot()
    while i < len(ops):
        if ops[i] == "-d" and i + 1 < len(ops):
            for g in nodos(raiz, ops[i + 1]):
                if g is raiz:
                    falla("no se puede borrar /gameList")
                raiz.remove(g)
            i += 2
        elif ops[i] == "-s" and ops[i + 2:i + 5] == ["-t", "elem", "-n"] and ops[i + 6:i + 7] == ["-v"] \
                and i + 7 < len(ops):
            for n in nodos(raiz, ops[i + 1]):
                ET.SubElement(n, ops[i + 5]).text = ops[i + 7] or None
            i += 8
        else:
            falla("opcion no soportada: " + " ".join(ops[i:]))
    if hasattr(ET, "indent"):
        ET.indent(arbol, "\t")
    tmp = archivo + ".mgtmp"
    arbol.write(tmp, encoding="utf-8", xml_declaration=True)
    with open(tmp, "a") as f:
        f.write("\n")
    os.chmod(tmp, os.stat(archivo).st_mode & 0o7777)
    os.replace(tmp, archivo)

def sel(args):
    if len(args) < 4 or args[0] != "-t":
        falla("solo se admite sel -t")
    archivo, ops = args[-1], args[1:-1]
    raiz = leer(archivo).getroot()
    if ops[0] == "-v" and len(ops) == 2 and re.fullmatch(r"count\((.*)\)", ops[1]):
        print(len(nodos(raiz, ops[1][6:-1])))
    elif ops[0] == "-m" and len(ops) > 1:
        salida, elegidos = [], nodos(raiz, ops[1])
        for g in elegidos:
            i = 2
            while i < len(ops):
                if ops[i] == "-v" and i + 1 < len(ops):
                    salida.append(g.findtext(ops[i + 1]) or "")
                    i += 2
                elif ops[i] == "-n":
                    salida.append("\n")
                    i += 1
                else:
                    falla("opcion no soportada: " + ops[i])
        sys.stdout.write("".join(salida))
        sys.exit(0 if elegidos else 1)      # como xmlstarlet: 1 si no hay coincidencias
    else:
        falla("solo se admite sel -t -v count(...) o sel -t -m")

if sys.argv[1:2] == ["ed"]:
    ed(sys.argv[2:])
elif sys.argv[1:2] == ["sel"]:
    sel(sys.argv[2:])
else:
    falla("orden no soportada: " + " ".join(sys.argv[1:]))
MG_PY
}
fi

# gamelist_poner GAMELIST RUTA_JUEGO campo=valor ...   (name=, desc=, image=, video=...)
# Borra la entrada anterior con la misma ruta y crea una nueva (idempotente).
# Los campos vacios no se escriben.
gamelist_poner() {
    local gl="$1" ruta="$2" par args=()
    shift 2
    [ -f "$gl" ] || echo '<?xml version="1.0"?><gameList></gameList>' > "$gl"
    respaldar "$gl"
    xmlstarlet ed -L -d "/gameList/game[path=\"$ruta\"]" "$gl" || return 1
    args=(-s "/gameList" -t elem -n "game" -v ""
          -s "/gameList/game[last()]" -t elem -n "path" -v "$ruta")
    for par in "$@"; do
        [ -n "${par#*=}" ] && args+=(-s "/gameList/game[last()]" -t elem -n "${par%%=*}" -v "${par#*=}")
    done
    xmlstarlet ed -L "${args[@]}" "$gl"
}

# ------------------------------------------------------------------ espacio

# sin_espacio NOMBRE NECESARIO_KB LIBRE_KB -> explica cuanto liberar y como
sin_espacio() {
    local falta=$(( $2 - $3 ))
    log "Sin espacio para $1: necesario_kb=$2 libre_kb=$3"
    dialog --backtitle "$MG_TITULO" --title "Espacio insuficiente" --ok-label "Entendido" --no-collapse --msgbox "
No hay espacio suficiente para instalar $1.

   Necesario:       $(humano_kb "$2")
   Libre ahora:     $(humano_kb "$3")
   Debes liberar:   $(humano_kb "$falta") como minimo

Para liberar espacio, borra juegos que ya no uses desde el
explorador de archivos (F1), en la seccion Editar > Quitar.

Luego vuelve a Mundo Games Toolbox > Descargas e intentalo
de nuevo. Si necesitas ayuda, contacta a Mundo Games." 18 68 2>&1 >/dev/tty
}

# espacio_ok NOMBRE NECESARIO_KB OCUPA_KB -> 0 = se puede instalar.
#   NECESARIO_KB: espacio libre que hace falta para instalar (sin el margen MG_MARGEN_KB).
#   OCUPA_KB: lo que quedara ocupado al terminar.
# Si no cabe, avisa (Espacio insuficiente) y devuelve 1. Si cabe pero al terminar quedarian menos de
# MG_JUSTO_KB libres, avisa de que el almacenamiento queda muy justo y pregunta si seguir.
espacio_ok() {
    local libre queda
    libre=$(libre_kb)
    if [ "$libre" -lt $(( $2 + MG_MARGEN_KB )) ]; then
        sin_espacio "$1" $(( $2 + MG_MARGEN_KB )) "$libre"
        return 1
    fi
    queda=$(( libre - $3 ))
    [ "$queda" -ge "$MG_JUSTO_KB" ] && return 0
    log "Poco espacio para $1: ocupa_kb=$3 libre_kb=$libre queda_kb=$queda"
    dialog --backtitle "$MG_TITULO" --title "Poco espacio" --yes-label "Instalar" --no-label "Cancelar" \
        --no-collapse --yesno "
Hay espacio para instalar $1, pero el almacenamiento
quedara muy justo para el sistema.

   Ocupara:          $(humano_kb "$3")
   Libre ahora:      $(humano_kb "$libre")
   Quedara libre:    $(humano_kb "$queda")

Te recomendamos liberar algo de espacio antes (2 o 3 GB),
borrando juegos que ya no uses desde el explorador de
archivos (F1), en la seccion Editar > Quitar.

Instalar de todas formas?" 20 68 2>&1 >/dev/tty
}

# ---------------------------------------------------------------- sistemas y runners

# instalar_sistema_es NOMBRE -> copia es_systems_NOMBRE.cfg si la consola no lo tiene.
# Devuelve 0 si ya estaba, 10 si se instalo (hay que reiniciar para verlo), 1 si fallo.
instalar_sistema_es() {
    local cfg="$MG_ES_CFG/es_systems_$1.cfg"
    [ -f "$cfg" ] && return 0
    mkdir -p "$(dirname "$cfg")"
    curl -fsSL --retry 3 -o "$cfg.mgtmp" "$MG_URL/sistemas/es_systems_$1.cfg" && mv "$cfg.mgtmp" "$cfg" \
        || { rm -f "$cfg.mgtmp"; return 1; }
    log "Sistema $1 agregado a EmulationStation"
    return 10
}

# runner_pendiente NOMBRE -> lee runners/NOMBRE.info del servidor y deja en RUNNER_ARCHIVO,
# RUNNER_SHA, RUNNER_BYTES y RUNNER_KB lo que habria que instalar. Devuelve 0 si hay que instalarlo,
# 1 si la consola ya lo tiene y 2 si no se pudo leer la informacion.
# Si la consola ya tiene un runner con ese nombre que no instalo la Toolbox (p. ej. una
# copia de la imagen maestra), se respeta y no se toca.
runner_pendiente() {
    local n="$1" dir="$MG_WINE_CUSTOM" tmpd
    tmpd=$(mktemp -d)
    curl -fsSL --retry 3 -o "$tmpd/info" "$MG_URL/runners/$n.info" || { rm -rf "$tmpd"; return 2; }
    RUNNER_ARCHIVO=$(leer_clave "$tmpd/info" ARCHIVO); RUNNER_SHA=$(leer_clave "$tmpd/info" SHA256)
    RUNNER_BYTES=$(leer_clave "$tmpd/info" BYTES);     RUNNER_KB=$(leer_clave "$tmpd/info" INSTALADO_KB)
    rm -rf "$tmpd"
    if [ -z "$RUNNER_ARCHIVO" ] || [ ${#RUNNER_SHA} -ne 64 ] || [ -z "$RUNNER_BYTES" ] || [ -z "$RUNNER_KB" ]; then
        return 2
    fi
    if [ -f "$dir/$n/.mundogames" ] && [ "$(cat "$dir/$n/.mundogames")" = "$RUNNER_SHA" ]; then return 1; fi
    if [ -d "$dir/$n" ] && [ ! -f "$dir/$n/.mundogames" ]; then
        log "Runner $n ya existe en la consola (no instalado por la Toolbox): se conserva"; return 1
    fi
    return 0
}

# instalar_runner NOMBRE -> Wine personalizado en /userdata/system/wine/custom/NOMBRE,
# descargado de la NAS (runners/NOMBRE.info + paquete tar.zst, verificado con SHA256).
# Si ya esta (ver runner_pendiente), no hace nada.
instalar_runner() {
    local n="$1" dir="$MG_WINE_CUSTOM" base="$MG_URL/runners"
    local archivo sha bytes kb paquete staging titulo="Instalando Wine $1"
    runner_pendiente "$n"
    case $? in
        1) return 0 ;;
        2) error "No se pudo obtener el programa $n."; return 1 ;;
    esac
    archivo="$RUNNER_ARCHIVO"; sha="$RUNNER_SHA"; bytes="$RUNNER_BYTES"; kb="$RUNNER_KB"
    if [ "$(libre_kb)" -lt $(( kb + bytes / 1024 + MG_MARGEN_KB )) ]; then
        sin_espacio "Wine $n" $(( kb + bytes / 1024 + MG_MARGEN_KB )) "$(libre_kb)"; return 1
    fi
    paquete="$MG_DESCARGAS/$archivo"; staging="$dir/.mg-$n"
    if [ "$(stat -c%s "$paquete" 2>/dev/null)" != "$bytes" ]; then
        descargar "$base/$archivo" "$paquete" $(( bytes / 1024 )) "$titulo" \
            || { error "La descarga de $n se interrumpio.\nVuelve a intentarlo: continuara donde se quedo."; return 1; }
    fi
    if [ "$(sha256sum "$paquete" | cut -d' ' -f1)" != "$sha" ]; then
        rm -f "$paquete"; error "La descarga de $n llego danada. Vuelve a intentarlo."; return 1
    fi
    rm -rf "$staging"; mkdir -p "$staging"
    extraer "$paquete" "$staging" "$kb" "$titulo" && [ -d "$staging/$n" ] \
        || { rm -rf "$staging"; error "No se pudo instalar $n."; return 1; }
    echo "$sha" > "$staging/$n/.mundogames"
    [ -d "$dir/$n" ] && mv "$dir/$n" "$staging/anterior"
    mv "$staging/$n" "$dir/$n"
    rm -rf "$staging" "$paquete"
    log "Runner $n instalado ($sha)"
}

# ---------------------------------------------------------------- descargas

# Barra de progreso mientras corre un proceso.
# vigilar_progreso PID TITULO TEXTO TOTAL_KB COMANDO_QUE_DEVUELVE_KB
# Muestra cuanto lleva, la velocidad de los ultimos segundos (no el promedio desde el inicio: asi se
# ve al momento si la conexion baja, y una descarga reanudada no aparenta ir mas rapido) y el tiempo
# que falta a esa velocidad.
vigilar_progreso() {
    local pid="$1" titulo="$2" texto="$3" total="$4" medir="$5"
    local actual pct ahora vel_kb resta vel_txt resta_txt
    local -a hist_t=() hist_kb=()          # muestras de los ultimos segundos
    [ "$total" -gt 0 ] 2>/dev/null || total=1
    while kill -0 "$pid" 2>/dev/null; do
        actual=$(eval "$medir" 2>/dev/null); actual=${actual:-0}
        pct=$((actual * 100 / total)); [ "$pct" -gt 99 ] && pct=99
        ahora=$(date +%s)
        hist_t+=("$ahora"); hist_kb+=("$actual")
        while [ ${#hist_t[@]} -gt 2 ] && [ $(( ahora - hist_t[0] )) -gt 5 ]; do   # ventana de ~5 s
            hist_t=("${hist_t[@]:1}"); hist_kb=("${hist_kb[@]:1}")
        done
        vel_txt="calculando..."; resta_txt="Tiempo restante: calculando..."
        if [ $(( ahora - hist_t[0] )) -ge 2 ]; then
            vel_kb=$(( (actual - hist_kb[0]) / (ahora - hist_t[0]) )); [ "$vel_kb" -lt 0 ] && vel_kb=0
            vel_txt=$(awk -v k="$vel_kb" 'BEGIN{ if (k >= 1024) printf "%.1f MB/s", k/1024; else printf "%d KB/s", k }')
            if [ "$vel_kb" -gt 0 ]; then
                resta=$(( (total - actual) / vel_kb )); [ "$resta" -lt 0 ] && resta=0
                if   [ "$resta" -ge 3600 ]; then resta_txt=$(printf 'Tiempo restante: %d h %02d min' $((resta / 3600)) $((resta % 3600 / 60)))
                elif [ "$resta" -ge 60 ];   then resta_txt="Tiempo restante: $(( (resta + 59) / 60 )) min"
                else                             resta_txt="Tiempo restante: menos de 1 min"
                fi
            else
                resta_txt="Tiempo restante: esperando datos..."
            fi
        fi
        echo "XXX"; echo "$pct"
        echo -e "\n$texto\n\n$(humano_kb "$actual") de $(humano_kb "$total")   ($vel_txt)\n$resta_txt"
        echo "XXX"
        sleep 1
    done | dialog --backtitle "$MG_TITULO" --title "$titulo" --gauge "" 12 64 0 2>&1 >/dev/tty
}

# descargar URL DESTINO TOTAL_KB TITULO -> reanuda si hay una descarga a medias
descargar() {
    local url="${1// /%20}" destino="$2" total="$3" titulo="$4" rc_file
    rc_file=$(mktemp)
    ( curl -fsL -C - --retry 10 --retry-delay 5 --retry-all-errors --connect-timeout 15 \
          -o "$destino" "$url"; echo $? > "$rc_file" ) &
    vigilar_progreso $! "$titulo" "Descargando..." "$total" "du -k '$destino' | cut -f1"
    wait
    local rc=$(cat "$rc_file"); rm -f "$rc_file"
    log "Descarga $url -> rc=$rc"
    [ "$rc" = "0" ]
}

# extraer ARCHIVO.tar.zst DIRECTORIO TOTAL_KB TITULO
extraer() {
    local archivo="$1" dir="$2" total="$3" titulo="$4" rc_file
    rc_file=$(mktemp)
    ( set -o pipefail; zstd -dcq "$archivo" | tar -xf - -C "$dir"; echo $? > "$rc_file" ) &
    vigilar_progreso $! "$titulo" "Instalando archivos..." "$total" "du -sk '$dir' | cut -f1"
    wait
    local rc=$(cat "$rc_file"); rm -f "$rc_file"
    log "Extraccion $archivo -> rc=$rc"
    [ "$rc" = "0" ]
}

# extraer_botella ARCHIVO.tar.zst DIRECTORIO TOTAL_KB TITULO
# Como extraer, pero conserva lo que necesita la capa overlay de un .wsquashfs:
# atributos trusted.overlay.* (origin, impure, uuid) y marcas de borrado (dispositivos 0,0).
extraer_botella() {
    local archivo="$1" dir="$2" total="$3" titulo="$4" rc_file
    rc_file=$(mktemp)
    ( set -o pipefail
      zstd -dcq "$archivo" | tar --xattrs --xattrs-include='trusted.overlay.*' --numeric-owner -xf - -C "$dir"
      echo $? > "$rc_file" ) &
    vigilar_progreso $! "$titulo" "Instalando configuracion de Wine..." "$total" "du -sk '$dir' | cut -f1"
    wait
    local rc=$(cat "$rc_file"); rm -f "$rc_file"
    log "Extraccion botella $archivo -> rc=$rc"
    [ "$rc" = "0" ]
}

# descargar_y_extraer URL DIRECTORIO TOTAL_KB TITULO SHA_ESPERADO
# Para consolas con poco espacio: no guarda el archivo comprimido.
# La suma SHA256 se calcula mientras se descarga; si no coincide, se descarta todo.
descargar_y_extraer() {
    local url="${1// /%20}" dir="$2" total="$3" titulo="$4" sha="$5" rc_file sha_file
    rc_file=$(mktemp); sha_file=$(mktemp)
    ( set -o pipefail
      curl -fsL --retry 5 --retry-delay 5 --connect-timeout 15 "$url" \
        | tee >(sha256sum | cut -d' ' -f1 > "$sha_file") \
        | zstd -dcq | tar -xf - -C "$dir"
      echo $? > "$rc_file" ) &
    vigilar_progreso $! "$titulo" "Descargando e instalando..." "$total" "du -sk '$dir' | cut -f1"
    wait
    for _ in $(seq 20); do [ -s "$sha_file" ] && break; sleep 0.5; done    # sha256sum termina un poco despues
    local rc=$(cat "$rc_file") real=$(cat "$sha_file"); rm -f "$rc_file" "$sha_file"
    log "Descarga directa $url -> rc=$rc sha=$real"
    [ "$rc" = "0" ] || return 1
    [ "$real" = "$sha" ] || { log "SHA256 no coincide (esperado $sha)"; return 2; }
}
