#!/usr/bin/env bash
set -euo pipefail

INSTANCE_NAME="${1:-Hellcraft}"
BASE_URL="${2:-https://games.computer-wizard.com.au/hellcraft}"
DOWNLOAD_URL="${BASE_URL%/}/downloads/hellcraft-latest.zip"
UA="hellcraft-installer"

prism_instances_dir() {
  case "$(uname -s)" in
    Linux*)
      if [[ -d "${HOME}/.var/app/org.prismlauncher.PrismLauncher/data/PrismLauncher/instances" ]]; then
        printf '%s\n' "${HOME}/.var/app/org.prismlauncher.PrismLauncher/data/PrismLauncher/instances"
      else
        printf '%s\n' "${HOME}/.local/share/PrismLauncher/instances"
      fi
      ;;
    Darwin*)
      printf '%s\n' "${HOME}/Library/Application Support/PrismLauncher/instances"
      ;;
    MINGW*|MSYS*|CYGWIN*)
      printf '%s\n' "${APPDATA:-${HOME}/AppData/Roaming}/PrismLauncher/instances"
      ;;
    *)
      printf '%s\n' "${HOME}/.local/share/PrismLauncher/instances"
      ;;
  esac
}

PRISM_ROOT="$(prism_instances_dir)/${INSTANCE_NAME}"
MC_DIR="${PRISM_ROOT}/.minecraft"

ensure_instance_metadata() {
  mkdir -p "$PRISM_ROOT" "$MC_DIR"

  if [[ ! -f "$PRISM_ROOT/instance.cfg" ]]; then
    cat > "$PRISM_ROOT/instance.cfg" <<'EOF'
[General]
ConfigVersion=1.3
InstanceType=OneSix
iconKey=default
name=Hellcraft
EOF
  fi

  if [[ ! -f "$PRISM_ROOT/mmc-pack.json" ]]; then
    cat > "$PRISM_ROOT/mmc-pack.json" <<'EOF'
{
    "components": [
        {
            "cachedName": "LWJGL 3",
            "cachedVersion": "3.3.3",
            "cachedVolatile": true,
            "dependencyOnly": true,
            "uid": "org.lwjgl3",
            "version": "3.3.3"
        },
        {
            "cachedName": "Minecraft",
            "cachedRequires": [
                {
                    "suggests": "3.3.3",
                    "uid": "org.lwjgl3"
                }
            ],
            "cachedVersion": "1.21.1",
            "important": true,
            "uid": "net.minecraft",
            "version": "1.21.1"
        },
        {
            "cachedName": "NeoForge",
            "cachedRequires": [
                {
                    "equals": "1.21.1",
                    "uid": "net.minecraft"
                }
            ],
            "cachedVersion": "21.1.242",
            "uid": "net.neoforged",
            "version": "21.1.242"
        }
    ],
    "formatVersion": 1
}
EOF
  fi
}

ensure_instance_metadata

tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT

archive="${tmpdir}/hellcraft-latest.zip"

echo "→ Downloading Hellcraft pack from ${DOWNLOAD_URL}"
curl -fsSL -A "$UA" -o "$archive" "$DOWNLOAD_URL"

echo "→ Updating ${INSTANCE_NAME}"
mkdir -p "$MC_DIR/mods" "$MC_DIR/config" "$MC_DIR/resourcepacks" "$MC_DIR/shaderpacks"
find "$MC_DIR/mods" -maxdepth 1 \( \
  -name 'hellcraft-*.jar' -o \
  -name 'player-animation-lib*.jar' -o \
  -name 'geckolib-*.jar' \
\) -delete

python3 - "$archive" "$MC_DIR" <<'PY'
from pathlib import Path
import shutil
import sys
import zipfile

archive = Path(sys.argv[1])
mc_dir = Path(sys.argv[2])

with zipfile.ZipFile(archive) as zf:
    for member in zf.namelist():
        if not member.startswith(".minecraft/"):
            continue
        rel = Path(member).relative_to(".minecraft")
        if not rel.parts:
            continue
        target = mc_dir / rel
        if member.endswith("/"):
            target.mkdir(parents=True, exist_ok=True)
            continue
        target.parent.mkdir(parents=True, exist_ok=True)
        with zf.open(member) as src, target.open("wb") as dst:
            shutil.copyfileobj(src, dst)
PY

echo "Done."
echo "Launch '${INSTANCE_NAME}' from Prism as normal."
echo "World saves were not touched."
