#!/usr/bin/env bash
# Adds a "Minenite" profile to the official Minecraft launcher.
set -euo pipefail
SITE="${MINENITE_SITE:-https://play.minenite.net}"
MC="${MINENITE_MINECRAFT_DIR:-$HOME/.minecraft}"
GAME="$MC/minenite"
BIN="$GAME/bin"
LIB="$MC/libraries/dev/horizon/bridge/1.0.0"
VER="$MC/versions/minenite-26.3"

say() { printf '\n%s\n' "$1"; }

if [[ ! -f "$MC/launcher_profiles.json" ]]; then
  echo "Open the Minecraft launcher once, then run this again."
  exit 1
fi
if [[ ! -f "$MC/versions/26.3/26.3.json" ]]; then
  echo "Play Minecraft Java 26.3 once in the Minecraft launcher, then run this again."
  exit 1
fi
command -v python3 >/dev/null || { echo "python3 is required."; exit 1; }
command -v curl >/dev/null || { echo "curl is required."; exit 1; }

mkdir -p "$BIN" "$LIB" "$VER" "$GAME/horizon-mods"
MANIFEST="$(mktemp)"
trap 'rm -f "$MANIFEST"' EXIT
curl -fsSL "$SITE/client/version.json" -o "$MANIFEST"

say "1/5  Downloading the Minenite client"
python3 - "$MANIFEST" "$BIN" "$GAME" "$SITE" <<'PY'
import hashlib, json, os, pathlib, sys, urllib.request
manifest, bindir, game, site = sys.argv[1:]
data = json.load(open(manifest))
pack = next(c for c in data["clients"] if c.get("os") == "linux")
want = {"horizon-client", "horizon-mods/orbital.hmod", "horizon-mods/minenite.hmod", "horizon-mods.txt"}
bindir, game = pathlib.Path(bindir), pathlib.Path(game)

def dest(rel):
    if rel == "horizon-client":
        return bindir / "horizon-client"
    return game / rel

for f in pack["files"]:
    if f["path"] not in want:
        continue
    url = f["url"]
    if url.startswith("./"):
        url = site.rstrip("/") + "/" + url[2:]
    elif url.startswith("/"):
        url = site.rstrip("/") + url
    target = dest(f["path"])
    target.parent.mkdir(parents=True, exist_ok=True)
    if target.is_file():
        h = hashlib.sha256()
        with target.open("rb") as fh:
            for chunk in iter(lambda: fh.read(1 << 20), b""):
                h.update(chunk)
        if h.hexdigest() == f["sha256"]:
            print(f"  already have {f['path']}")
            continue
    print(f"  {f['path']}")
    tmp = target.with_suffix(target.suffix + ".part")
    urllib.request.urlretrieve(url, tmp)
    got = hashlib.sha256(tmp.read_bytes()).hexdigest()
    if got != f["sha256"]:
        tmp.unlink(missing_ok=True)
        raise SystemExit(f"bad download {f['path']}")
    tmp.replace(target)
    if f["path"] == "horizon-client":
        target.chmod(0o755)
PY

say "2/5  Installing the launcher bridge"
curl -fsSL "$SITE/client/launcher/bridge.jar" -o "$LIB/bridge-1.0.0.jar"
python3 - "$LIB/bridge-1.0.0.jar" "$VER/minenite-26.3.json" "$SITE" <<'PY'
import hashlib, json, sys
from datetime import datetime, timezone
jar, out, site = sys.argv[1:]
sha1 = hashlib.sha1(open(jar, "rb").read()).hexdigest()
size = __import__("os").path.getsize(jar)
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S+00:00")
json.dump({
    "id": "minenite-26.3",
    "inheritsFrom": "26.3",
    "type": "release",
    "time": now,
    "releaseTime": now,
    "minimumLauncherVersion": 21,
    "mainClass": "dev.horizon.bridge.Main",
    "libraries": [{
        "name": "dev.horizon:bridge:1.0.0",
        "downloads": {"artifact": {
            "path": "dev/horizon/bridge/1.0.0/bridge-1.0.0.jar",
            "sha1": sha1,
            "size": size,
            "url": site.rstrip("/") + "/client/launcher/bridges/" + sha1 + ".jar",
        }},
    }],
}, open(out, "w"), indent=2)
open(out, "a").write("\n")
print(f"  bridge sha1 {sha1}")
PY

say "3/5  Adding the Minenite profile"
python3 - "$MC" "$SITE" <<'PY'
import base64, json, sys, urllib.request, uuid
from datetime import datetime, timezone
from pathlib import Path
mc = Path(sys.argv[1])
site = sys.argv[2].rstrip("/")
profiles_path = mc / "launcher_profiles.json"
data = json.loads(profiles_path.read_text())
profiles = data.setdefault("profiles", {})
existing = next((i for i, p in profiles.items()
                 if p.get("lastVersionId") in ("horizon-26.3", "minenite-26.3")
                 or p.get("name") == "Horizon"), None)
pid = existing or uuid.uuid4().hex
stamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
prev = profiles.get(pid, {})
logo = urllib.request.urlopen(site + "/minenite-logo.png").read()
icon = "data:image/png;base64," + base64.b64encode(logo).decode()
profiles[pid] = {
    "created": prev.get("created", stamp),
    "icon": icon,
    "lastUsed": stamp,
    "lastVersionId": "minenite-26.3",
    "name": "Minenite",
    "type": "custom",
    "gameDir": str(mc / "minenite"),
}
data["selectedProfile"] = pid
profiles_path.write_text(json.dumps(data, indent=2) + "\n")
print("  profile Minenite")
PY

say "4/5  Minenite Ray shaders"
python3 - "$GAME" "$SITE" <<'PY'
import hashlib, json, pathlib, sys, urllib.request
game, site = pathlib.Path(sys.argv[1]), sys.argv[2].rstrip("/")
manifest = json.load(urllib.request.urlopen(site + "/client/launcher/shaders/minenite-ray.json"))
dest = game / "shaderpacks" / manifest["id"]
for item in manifest["files"]:
    rel = pathlib.PurePosixPath(item["path"])
    if any(part in ("", ".", "..") for part in rel.parts):
        raise SystemExit(f"bad shader path {item['path']}")
    target = dest.joinpath(*rel.parts)
    target.parent.mkdir(parents=True, exist_ok=True)
    if target.is_file():
        have = hashlib.sha256(target.read_bytes()).hexdigest()
        if have == item["sha256"]:
            continue
    url = f"{site}/client/launcher/shaders/{manifest['id']}/{item['path']}"
    data = urllib.request.urlopen(url).read()
    if hashlib.sha256(data).hexdigest() != item["sha256"]:
        raise SystemExit(f"bad shader download {item['path']}")
    target.write_bytes(data)
    print(f"  {item['path']}")
gfx = game / "horizon-graphics.txt"
text = gfx.read_text() if gfx.is_file() else ""
current = ""
kept = []
for line in text.splitlines():
    if line.startswith("pickedShaderPack:"):
        current = line.split(":", 1)[1]
    elif line:
        kept.append(line)
if current in ("", "minenite-ray", "horizon:minenite_ray"):
    current = "minenite-ray"
kept.append(f"pickedShaderPack:{current}")
gfx.write_text("\n".join(kept) + "\n")
print("  Minenite Ray is the shader pack")
PY

say "5/5  Prepared game files"
RESOURCES=""
cands=()
[[ -n "${MINENITE_RESOURCES:-}" ]] && cands+=("$MINENITE_RESOURCES")
cands+=("$HOME/.local/horizon-client/26.3" "$HOME/Desktop/MINENITE/horizon/.local/horizon-client/26.3" "$GAME/26.3")
if [[ -d "$HOME/.local/share/horizon-launcher/versions" ]]; then
  while IFS= read -r d; do cands+=("$d"); done < <(find "$HOME/.local/share/horizon-launcher/versions" -type d -path '*/.local/horizon-client/26.3' 2>/dev/null | head -5)
fi
if [[ -d "$HOME/Desktop/MINENITE/launcher/state/versions" ]]; then
  while IFS= read -r d; do cands+=("$d"); done < <(find "$HOME/Desktop/MINENITE/launcher/state/versions" -type d -path '*/.local/horizon-client/26.3' 2>/dev/null | head -5)
fi
for c in "${cands[@]}"; do
  if [[ -f "$c/horizon-resources.json" ]]; then RESOURCES="$c"; break; fi
done

cat > "$GAME/bridge.properties" <<EOF
# Written by the Minenite launcher installer.
client=$BIN/horizon-client
EOF
if [[ -n "$RESOURCES" ]]; then
  printf 'resources=%s\n' "$RESOURCES" >> "$GAME/bridge.properties"
  echo
  echo "Done. Open the Minecraft launcher, choose Minenite, and press Play."
else
  cat >> "$GAME/bridge.properties" <<EOF
# resources=/path/to/the/folder/with/horizon-resources.json
EOF
  echo
  echo "The Minenite profile is installed, but prepared Minecraft 26.3 files were not found."
  echo "Open the Horizon launcher, press Prepare, then run this installer again."
  echo "Or set resources= in $GAME/bridge.properties to the folder that contains horizon-resources.json."
  exit 1
fi
