#!/usr/bin/env bash
set -e
if [[ "$OSTYPE" == "darwin"* ]]; then
  DEFAULT_DIR="$HOME/Library/Application Support/minecraft/mods"
else
  DEFAULT_DIR="$HOME/.minecraft/mods"
fi
MODS_DIR="${1:-$DEFAULT_DIR}"
mkdir -p "$MODS_DIR"

echo "SqushMC Mod Autoloader -> $MODS_DIR"
python3 - <<PY
import hashlib, json, os, urllib.request

mods_dir = os.path.expanduser("$MODS_DIR")
with urllib.request.urlopen("https://mods.sqush.dev/manifest.json") as r:
    manifest = json.loads(r.read().decode())

active = {m["filename"]: m for m in manifest["mods"] if m.get("enabled", True)}
for fn in os.listdir(mods_dir):
    if fn.endswith(".jar") and fn not in active:
        print(f"[Entferne] {fn}")
        os.remove(os.path.join(mods_dir, fn))

for idx, (fn, m) in enumerate(active.items(), 1):
    dest = os.path.join(mods_dir, fn)
    need = True
    if os.path.exists(dest):
        h = hashlib.sha256(open(dest, "rb").read()).hexdigest().lower()
        if h == m["sha256"].lower():
            need = False
    if need:
        print(f"[{idx}/{len(active)}] Lade {m['title']}...")
        urllib.request.urlretrieve(m["url"], dest)

print(f"Fertig! {len(active)} Mods synchronisiert. Server: minecraft.sqush.dev")
PY
