#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
[[ $EUID -eq 0 ]] || { echo 'Ejecute: sudo bash install.sh'; exit 1; }
[[ $(uname -s) == Linux ]] || { echo 'Se requiere Ubuntu Linux con systemd.'; exit 1; }
HERE=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
# The hosted script can bootstrap itself; no compiler or Node is installed.
missing=()
for entry in 'curl:curl' 'python3:python3' 'sha256sum:coreutils'; do
 command -v "${entry%%:*}" >/dev/null || missing+=("${entry#*:}")
done
if (( ${#missing[@]} )); then apt-get update; apt-get install -y --no-install-recommends "${missing[@]}" ca-certificates; fi
if [[ ! -f $HERE/scripts/common.sh ]]; then
 tmp=$(mktemp -d); trap 'rm -rf -- "$tmp"' EXIT
 version=1.0.4
 name="nodo7-247-creator-v$version.tar.gz"
 url="https://creator.nodo7.online/releases/v$version"
 curl -fSL --proto '=https' --tlsv1.2 "$url/$name" -o "$tmp/$name"
 curl -fSL --proto '=https' --tlsv1.2 "$url/SHA256SUMS.txt" -o "$tmp/SHA256SUMS.txt"
 sum=$(awk -v n="$name" '$2==n || $2=="*"n {print $1}' "$tmp/SHA256SUMS.txt")
 [[ $sum =~ ^[a-f0-9]{64}$ ]] || { echo 'Checksum inválido'; exit 1; }
 printf '%s  %s\n' "$sum" "$tmp/$name" | sha256sum -c -
 python3 - "$tmp/$name" "$tmp" <<'PY'
import pathlib,sys,tarfile
root=pathlib.Path(sys.argv[2]).resolve()
with tarfile.open(sys.argv[1]) as t:
 total=0
 for m in t.getmembers():
  p=(root/m.name).resolve(); total+=m.size
  if root not in p.parents or not(m.isfile() or m.isdir()) or total>3*1024**3: raise ValueError('Paquete inseguro')
 t.extractall(root)
PY
 bash "$tmp/nodo7-247-creator/install.sh"
 exit
fi
# shellcheck source=scripts/common.sh
source "$HERE/scripts/common.sh"
platform
[[ ! -e $APP && ! -e $DATA/config.json ]] || { echo 'Ya existe una instalación. Use update.sh.'; exit 1; }
[[ -x $HERE/bin/linux-$ARCH/nodo7-247 && -x $HERE/bin/linux-$ARCH/ffmpeg ]] || { echo 'Use el paquete de distribución compilado.'; exit 1; }
read -r -p 'Puerto [2477]: ' port; port=${port:-2477}
[[ $port =~ ^[0-9]+$ && $port -ge 1024 && $port -le 65535 ]] || { echo 'Puerto inválido (1024–65535)'; exit 1; }
read -r -p 'Usuario administrador: ' admin
read -r -s -p 'Contraseña (12–72 bytes): ' password; echo
read -r -s -p 'Repetir contraseña: ' repeat; echo
[[ $password == "$repeat" && ${#password} -ge 12 && ${#password} -le 72 && -n $admin ]] || { echo 'Usuario o contraseña inválidos'; exit 1; }
read -r -p 'Ruta principal de medios [/home]: ' media; media=${media:-/home}
[[ $media == /* && -d $media ]] || { echo 'La ruta debe ser un directorio absoluto existente.'; exit 1; }
read -r -p '¿Importar Creator247 existente? [S/N]: ' import_old
old_db=''
if [[ $import_old =~ ^[Ss]$ ]]; then read -r -p 'Ruta de una COPIA consistente de iptv.db: ' old_db; [[ -f $old_db ]] || exit 1; fi
getent group nodo7 >/dev/null || groupadd --system nodo7
id nodo7 >/dev/null 2>&1 || useradd --system --gid nodo7 --home-dir "$DATA" --shell /usr/sbin/nologin nodo7
install -d -m 0700 -o nodo7 -g nodo7 "$DATA" "$DATA/posters" "$DATA/backups" "$DATA/logs" "$DATA/streams"
install_tree "$HERE" "$APP"
"$APP/bin/ffmpeg" -version >/dev/null
"$APP/bin/ffprobe" -version >/dev/null
printf '%s\n' "$password" | runuser -u nodo7 -- "$APP/bin/nodo7-247" -data "$DATA" -port "$port" -media-root "$media" -admin "$admin" init
unset password repeat
if [[ -n $old_db ]]; then
 "$APP/bin/nodo7-247" -source "$old_db" import
 read -r -p '¿Confirmar importación de los datos mostrados? [S/N]: ' yes
 if [[ $yes =~ ^[Ss]$ ]]; then "$APP/bin/nodo7-247" -source "$old_db" -confirm import; fi
 chown -R nodo7:nodo7 "$DATA"
fi
install -m 0644 "$APP/deploy/nodo7-247.service" /etc/systemd/system/nodo7-247.service
systemctl daemon-reload
systemctl enable --now nodo7-247.service
health "$port" || { journalctl -u nodo7-247.service -n 30 --no-pager; exit 1; }
ip=$(hostname -I | awk '{print $1}')
echo "NODO 7 listo: http://${ip:-SERVER-IP}:$port"
echo "Medios: $media — el usuario nodo7 necesita permisos de lectura/travesía. Consulte README."
echo 'FFmpeg privado: /opt/nodo7-247/bin/ffmpeg. StreamMaster no se ha modificado.'
