#!/bin/bash
# Aetherbound installer for macOS (TLauncher / official launcher).
# Double-click in Finder. Installs Forge 1.20.1 + a local Java 17 JRE.

set -e
BASE_URL="https://pack.riegergeri.com"
ZIP_NAME="aetherbound-client-1.20.1.zip"
ZIP_URL="$BASE_URL/$ZIP_NAME"
SERVERS_DAT_URL="$BASE_URL/servers.dat"
FORGE_INSTALLER_URL="$BASE_URL/forge-1.20.1-47.4.9-installer.jar"
FORGE_VERSION="1.20.1-forge-47.4.9"

cd "$(dirname "$0")"

clear
echo "============================================="
echo "         Aetherbound installer (macOS)"
echo "============================================="
echo

# 1. Pick .minecraft.
MC=""
for d in \
  "$HOME/Library/Application Support/minecraft" \
  "$HOME/Library/Application Support/.minecraft" \
  "$HOME/.minecraft"; do
  if [ -d "$d" ]; then MC="$d"; break; fi
done
if [ -z "$MC" ]; then
  MC="$HOME/Library/Application Support/minecraft"
  mkdir -p "$MC"
fi
echo "Game folder: $MC"
echo

# 2a. Clean any partial Forge install / locked natives dir from a previous
#     failed launch. TLauncher errors with "A fájl írási művelete tilos
#     .../versions/1.20.1-forge-47.4.9/natives" if a lockfile is left behind.
if [ -d "$MC/versions/1.20.1-forge-47.4.9/natives" ]; then
  echo "Cleaning stale natives dir..."
  rm -rf "$MC/versions/1.20.1-forge-47.4.9/natives"
fi
# Fix any read-only / wrong-owner files left by a previous install.
chmod -R u+w "$MC" 2>/dev/null || true
xattr -dr com.apple.quarantine "$MC" 2>/dev/null || true

# 2. Ensure a Java 17 JRE lives inside .minecraft (Forge 1.20.1 cannot run on
#    21; TLauncher's bundled jre-21 is what crashes the pack on first launch).
JDK_HOME="$MC/aetherbound-jdk17"
JAVA17="$JDK_HOME/Contents/Home/bin/java"
if [ ! -x "$JAVA17" ]; then
  echo "Downloading Java 17 JRE (~50 MB)..."
  ARCH="$(uname -m)"
  case "$ARCH" in
    arm64|aarch64) ADOPTIUM_ARCH="aarch64" ;;
    x86_64)        ADOPTIUM_ARCH="x64" ;;
    *) echo "Unsupported CPU: $ARCH"; exit 1 ;;
  esac
  JRE_URL="https://api.adoptium.net/v3/binary/latest/17/ga/mac/${ADOPTIUM_ARCH}/jre/hotspot/normal/eclipse"
  TMP_JRE="$(mktemp -t jre17).tar.gz"
  curl -L --progress-bar -o "$TMP_JRE" "$JRE_URL"
  rm -rf "$JDK_HOME"
  mkdir -p "$JDK_HOME"
  tar -xzf "$TMP_JRE" -C "$JDK_HOME" --strip-components=1
  rm -f "$TMP_JRE"
  if [ ! -x "$JAVA17" ]; then
    echo "Java 17 extracted but binary not found at $JAVA17"
    ls -la "$JDK_HOME" || true
    exit 1
  fi
fi
echo "Java 17: $JAVA17"
"$JAVA17" -version
echo

# 3. Mods. Back up existing mods folder, then copy ours in.
if [ -d "$MC/mods" ] && [ -n "$(ls -A "$MC/mods" 2>/dev/null)" ]; then
  STAMP="$(date +%Y%m%d-%H%M%S)"
  echo "Existing mods/ found — moved to mods-backup-$STAMP/"
  mv "$MC/mods" "$MC/mods-backup-$STAMP"
fi
mkdir -p "$MC/mods"

TMP="$(mktemp -d -t aetherbound)"
trap 'rm -rf "$TMP"' EXIT
echo "Downloading mods (~530 MB)... this can take a few minutes."
curl -L --progress-bar -o "$TMP/pack.zip" "$ZIP_URL"
echo "Unpacking..."
unzip -q "$TMP/pack.zip" -d "$TMP/extract"
if [ -d "$TMP/extract/mods" ]; then
  cp "$TMP"/extract/mods/*.jar "$MC/mods/"
else
  find "$TMP/extract" -name '*.jar' -exec cp {} "$MC/mods/" \;
fi
JAR_COUNT=$(ls -1 "$MC/mods"/*.jar 2>/dev/null | wc -l | tr -d ' ')
echo "Installed $JAR_COUNT mod files."
echo

# 4. Forge client install — registers $FORGE_VERSION in the version list so
#    TLauncher / the official launcher can pick it instead of defaulting to
#    1.21.x.
if [ ! -d "$MC/versions/$FORGE_VERSION" ]; then
  echo "Installing Forge $FORGE_VERSION client..."
  curl -fsSL -o "$TMP/forge.jar" "$FORGE_INSTALLER_URL"
  # Ensure launcher_profiles.json exists or the Forge installer refuses to run.
  if [ ! -f "$MC/launcher_profiles.json" ]; then
    echo '{"profiles":{},"settings":{},"version":3}' > "$MC/launcher_profiles.json"
  fi
  "$JAVA17" -jar "$TMP/forge.jar" --installClient "$MC"
fi

# 5. launcher_profiles.json — write an Aetherbound profile that pins Forge
#    1.20.1 and our bundled Java 17. Uses python3 (ships with macOS).
PROFILES="$MC/launcher_profiles.json"
if [ ! -f "$PROFILES" ]; then
  echo '{"profiles":{},"settings":{},"version":3}' > "$PROFILES"
fi
python3 - <<PY
import json, os
p = "$PROFILES"
data = json.load(open(p))
data.setdefault("profiles", {})
data["profiles"]["aetherbound"] = {
    "name": "Aetherbound (Forge 1.20.1)",
    "type": "custom",
    "lastVersionId": "$FORGE_VERSION",
    "javaDir": "$JAVA17",
    "javaArgs": "-Xmx6G -Xms2G -XX:+UseG1GC",
    "gameDir": "$MC",
    "icon": "Furnace",
}
json.dump(data, open(p, "w"), indent=2)
PY
echo "Profile 'Aetherbound (Forge 1.20.1)' written."

# 6. Server list. Non-fatal — losing the prefilled server list is not worth
#    aborting the whole install over (an immutable old .bak file would do it).
set +e
if [ -f "$MC/servers.dat" ]; then
  chflags nouchg "$MC/servers.dat" 2>/dev/null || true
  chflags nouchg "$MC/servers.dat.bak" 2>/dev/null || true
  rm -f "$MC/servers.dat.bak"
  cp -f "$MC/servers.dat" "$MC/servers.dat.bak" || \
    echo "(could not back up old servers.dat — continuing)"
fi
echo "Adding server: mc.riegergeri.com"
if ! curl -fsSL -o "$MC/servers.dat.new" "$SERVERS_DAT_URL"; then
  echo "(could not download server list — add mc.riegergeri.com manually in-game)"
else
  mv -f "$MC/servers.dat.new" "$MC/servers.dat"
fi
set -e

echo
echo "============================================="
echo "  Done!"
echo "============================================="
echo "TLauncher (cracked-friendly):"
echo "  1. Open TLauncher. Fully quit it first if it was running."
echo "  2. In the version dropdown pick:  Forge 1.20.1-47.4.9"
echo "     (TLauncher does NOT show the Aetherbound profile — it has its own"
echo "      profile system. The Forge version is what matters.)"
echo "  3. Settings -> Java -> Custom path:"
echo "       $JAVA17"
echo "  4. Click Play."
echo
echo "Official Mojang launcher:"
echo "  Pick the profile 'Aetherbound (Forge 1.20.1)' and hit Play."
echo
echo "Voice chat: ts.riegergeri.com  (TeamSpeak 3)"
echo
read -n 1 -s -r -p "Press any key to close this window..."
echo
