#!/bin/sh
# B70 Launcher - one-step bootstrap.
#   curl -fsSL https://xecores.com/downloads/get.sh | sh
# Fetches version.json for the current tarball URL + expected SHA256,
# downloads, verifies the checksum, extracts, and runs the rootless
# installer. No sudo, nothing outside ~/.local.
set -eu

BASE="https://xecores.com/downloads"
die() { printf 'error: %s\n' "$*" >&2; exit 1; }

fetch() {
    if command -v curl >/dev/null 2>&1; then curl -fsSL "$1"
    elif command -v wget >/dev/null 2>&1; then wget -qO- "$1"
    else die "need curl or wget to download"; fi
}

command -v python3 >/dev/null 2>&1 \
    || die "python3 not found - install Python 3.9+ first (Debian/Ubuntu: sudo apt install python3)."

meta=$(fetch "$BASE/version.json") || die "cannot reach xecores.com"
eval "$(printf '%s' "$meta" | python3 -c '
import json, sys, shlex
d = json.load(sys.stdin)
url = d["tarball_url"]; h = d["sha256"]
if not url.startswith("https://xecores.com/downloads/"):
    sys.exit("unexpected tarball_url in version.json")
print(f"URL={shlex.quote(url)} SUM={shlex.quote(h)}")' 2>/dev/null)" \
    || die "could not parse version.json"
: "${URL:?}" "${SUM:?}"

tmp=$(mktemp -d) || die "mktemp failed"
trap 'rm -rf "$tmp"' EXIT
tgz="$tmp/b70-launcher.tar.gz"

printf 'B70 Launcher bootstrap\n'
printf '  download : %s\n' "$URL"
fetch "$URL" > "$tgz" || die "download failed"

printf '%s  %s\n' "$SUM" "$tgz" | sha256sum -c - >/dev/null \
    || die "SHA256 mismatch - aborting. Do NOT run the extracted files; report this."
printf '  checksum : ok\n'

tar -xzf "$tgz" -C "$tmp" || die "extract failed"
src=$(find "$tmp" -maxdepth 1 -type d -name 'b70-launcher-*-linux-source' | head -1)
[ -n "$src" ] || die "unexpected archive layout"

sh "$src/packaging/install.sh"
printf '\nDone. Start it from your application menu, or run: b70-launcher\n'
printf '(add %s/.local/bin to PATH if the command is not found)\n' "$HOME"
