#!/bin/bash
# ============================================================================
#  JARVIS pour Linux : un seul fichier à lancer.
#     bash JARVIS-Linux.sh
#  Il télécharge la dernière version (signature vérifiée), l'installe dans ~/JARVIS-Linux,
#  ajoute JARVIS au menu des applications, puis lance JARVIS.  Ensuite : JARVIS est dans le menu.
# ============================================================================
command -v python3 >/dev/null 2>&1 || { echo "Il faut python3 : sudo apt install python3  (puis relance ce fichier)"; exit 1; }
DEST="${JARVIS_INSTALL_DIR:-$HOME/JARVIS-Linux}"
if [ -f "$DEST/VERSION" ] && [ -f "$DEST/jarvis-linux.sh" ] && [ ! -f "$DEST/.installation-en-cours" ] && [ "$1" != "--reparer" ]; then
  exec bash "$DEST/jarvis-linux.sh" "$@"
fi
python3 - "$DEST" <<'PY' || { echo; read -r -p "  Appuie sur Entrée pour fermer… " _; exit 1; }
import base64, hashlib, io, json, os, sys, time, urllib.request, zipfile
DEST = sys.argv[1]
SERVERS = [os.environ.get("JARVIS_SERVER") or "https://jarvis.link-host.fr", "https://jarvis-zelda.duckdns.org:8770", "http://jarvis-zelda.duckdns.org:8770", "http://192.168.1.23:8770"]
PUB = base64.b64decode(os.environ.get("JARVIS_PUBKEY_TEST") or "q7bRTQ2jqIHwbCwYOyBB99M3LhStZ+N4/D9VOrtUEp4=")
import hashlib
_P = 2 ** 255 - 19
_L = 2 ** 252 + 27742317777372353535851937790883648493
_D = -121665 * pow(121666, _P - 2, _P) % _P
_I = pow(2, (_P - 1) // 4, _P)


def _padd(a, b):
    x1, y1, z1, t1 = a
    x2, y2, z2, t2 = b
    A = (y1 - x1) * (y2 - x2) % _P
    B = (y1 + x1) * (y2 + x2) % _P
    C = t1 * 2 * _D * t2 % _P
    D = z1 * 2 * z2 % _P
    E, F, G, H = B - A, D - C, D + C, B + A
    return (E * F % _P, G * H % _P, F * G % _P, E * H % _P)


def _pmul(s: int, p):
    q = (0, 1, 1, 0)
    while s > 0:
        if s & 1:
            q = _padd(q, p)
        p = _padd(p, p)
        s >>= 1
    return q


def _peq(a, b) -> bool:
    return (a[0] * b[2] - b[0] * a[2]) % _P == 0 and (a[1] * b[2] - b[1] * a[2]) % _P == 0


def _recover_x(y: int, sign: int):
    if y >= _P:
        return None
    x2 = (y * y - 1) * pow(_D * y * y + 1, _P - 2, _P)
    if x2 == 0:
        return None if sign else 0
    x = pow(x2, (_P + 3) // 8, _P)
    if (x * x - x2) % _P:
        x = x * _I % _P
    if (x * x - x2) % _P:
        return None
    if (x & 1) != sign:
        x = _P - x
    return x


def _decompress(b: bytes):
    if len(b) != 32:
        return None
    y = int.from_bytes(b, "little")
    sign = y >> 255
    y &= (1 << 255) - 1
    x = _recover_x(y, sign)
    return None if x is None else (x, y, 1, x * y % _P)


_GY = 4 * pow(5, _P - 2, _P) % _P
_G = (_recover_x(_GY, 0), _GY, 1, _recover_x(_GY, 0) * _GY % _P)


def _pure_ed25519_verify(public: bytes, sig: bytes, msg: bytes) -> bool:
    if len(public) != 32 or len(sig) != 64:
        return False
    a = _decompress(public)
    r = _decompress(sig[:32])
    s = int.from_bytes(sig[32:], "little")
    if a is None or r is None or s >= _L:
        return False
    h = int.from_bytes(hashlib.sha512(sig[:32] + public + msg).digest(), "little") % _L
    return _peq(_pmul(s, _G), _padd(r, _pmul(h, a)))



def get(url, timeout=25):
    return urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "JARVIS-Installateur/1"}), timeout=timeout)
print("\n  ╔══════════════════════════════════════╗\n  ║     J . A . R . V . I . S            ║\n  ║     installation (une seule fois)    ║\n  ╚══════════════════════════════════════╝\n")
err = "serveur JARVIS injoignable (il est peut-être éteint : réessaie plus tard)"
for base in SERVERS:
    try:
        info = json.load(get(base + "/update/info?platform=linux", 15))
        ver, sha, sig = info["version"], info["sha256"], base64.b64decode(info["sig"])
    except Exception as e:
        continue
    if not _pure_ed25519_verify(PUB, sig, f"JARVIS-MAJ|linux|{ver}|{sha}".encode()):
        sys.exit("  ❌ Signature de la version invalide : téléchargement refusé par sécurité.")
    try:
        r = get(base + "/download/linux-zip", 60); total = int(r.headers.get("Content-Length") or info.get("size") or 0)
        buf, h, t0 = io.BytesIO(), hashlib.sha256(), time.time()
        while True:
            b = r.read(1 << 18)
            if not b: break
            buf.write(b); h.update(b); n = buf.tell()
            p = n / total if total else 0
            print(f"\r  [{'█' * int(p * 30)}{'░' * (30 - int(p * 30))}] {p * 100:3.0f} %  JARVIS {ver} · {n >> 20}/{total >> 20} Mo · {n / max(.1, time.time() - t0) / 1048576:.1f} Mo/s   ", end="", flush=True)
        if h.hexdigest() != sha:
            err = "fichier abîmé pendant le téléchargement"; continue
    except Exception as e:
        err = f"téléchargement impossible ({e})"; continue
    print("\n  📦 Installation…")
    os.makedirs(DEST, exist_ok=True)
    mark = os.path.join(DEST, ".installation-en-cours"); open(mark, "w").close()
    root = os.path.realpath(DEST)
    with zipfile.ZipFile(buf) as z:
        for it in z.infolist():
            parts = it.filename.replace("\\", "/").split("/", 1)
            if len(parts) < 2 or not parts[1] or it.is_dir() or parts[1].startswith(("data/", ".venv/")) or ".." in parts[1].split("/"):
                continue
            tgt = os.path.realpath(os.path.join(root, parts[1]))
            if not tgt.startswith(root + os.sep): continue
            os.makedirs(os.path.dirname(tgt), exist_ok=True)
            with open(tgt + ".install", "wb") as f: f.write(z.read(it))
            os.replace(tgt + ".install", tgt)
            mode = (it.external_attr >> 16) & 0o777
            os.chmod(tgt, 0o755 if (mode & 0o111 or tgt.endswith(".sh")) else 0o644)
    os.remove(mark)
    # raccourci dans le menu des applications
    try:
        app = os.path.expanduser("~/.local/share/applications"); os.makedirs(app, exist_ok=True)
        icon = os.path.join(DEST, "jarvis", "ui", "assets", "logo.png")
        with open(os.path.join(app, "jarvis.desktop"), "w") as f:
            f.write(f"[Desktop Entry]\nType=Application\nName=JARVIS\nComment=Assistant personnel\nExec=bash \"{DEST}/jarvis-linux.sh\"\n"
                    f"Icon={icon}\nTerminal=true\nCategories=Utility;\n")
    except OSError:
        pass
    print(f"  ✅ JARVIS {ver} est installé dans « {DEST} » (et dans le menu des applications).\n")
    sys.exit(0)
sys.exit("  ❌ " + err + "\n     Version zip : https://jarvis.link-host.fr/download/linux-zip")
PY
[ -n "$JARVIS_INSTALL_TEST" ] && { echo "LANCEMENT: $DEST"; exit 0; }
exec bash "$DEST/jarvis-linux.sh" "$@"
