#!/bin/bash
set -euo pipefail

ARTIFACT_ROOT="/opt/zlh/zpacks/minecraft/forge"

# Forge Versions + URLs
declare -A FORGE_MAP=(
  ["1.20.1"]="https://maven.minecraftforge.net/net/minecraftforge/forge/1.20.1-47.4.10/forge-1.20.1-47.4.10-installer.jar"
  ["1.19.2"]="https://maven.minecraftforge.net/net/minecraftforge/forge/1.19.2-43.5.0/forge-1.19.2-43.5.0-installer.jar"
  ["1.18.2"]="https://maven.minecraftforge.net/net/minecraftforge/forge/1.18.2-40.3.0/forge-1.18.2-40.3.0-installer.jar"
  ["1.12.2"]="https://maven.minecraftforge.net/net/minecraftforge/forge/1.12.2-14.23.5.2859/forge-1.12.2-14.23.5.2859-installer.jar"
)

echo "====================================================="
echo " ZeroLagHub Forge Installer Sync"
echo " Target directory: $ARTIFACT_ROOT"
echo "====================================================="

# Create root folder
mkdir -p "$ARTIFACT_ROOT"

for VERSION in "${!FORGE_MAP[@]}"; do
  URL="${FORGE_MAP[$VERSION]}"
  TARGET_DIR="$ARTIFACT_ROOT/$VERSION"
  TARGET_FILE="$TARGET_DIR/forge-installer.jar"

  echo ""
  echo "----------------------------------------"
  echo "Processing Forge $VERSION"
  echo "URL: $URL"
  echo "Directory: $TARGET_DIR"
  echo "----------------------------------------"

  # Remove old files
  echo " - Cleaning old installers..."
  rm -rf "$TARGET_DIR"
  mkdir -p "$TARGET_DIR"

  # Temp download path
  TMP_FILE="$TARGET_DIR/_download.tmp"

  echo " - Downloading..."
  if ! wget -q --show-progress -O "$TMP_FILE" "$URL"; then
    echo " ❌ Failed to download Forge $VERSION"
    rm -f "$TMP_FILE"
    continue
  fi

  # Validate
  if [[ ! -s "$TMP_FILE" ]]; then
    echo " ❌ ERROR: Downloaded file for $VERSION is empty"
    rm -f "$TMP_FILE"
    continue
  fi

  # Move into place
  mv "$TMP_FILE" "$TARGET_FILE"
  chmod 644 "$TARGET_FILE"

  echo " ✅ Forge $VERSION downloaded successfully"
  echo "     → $TARGET_FILE"
done

echo ""
echo "====================================================="
echo "  All Forge installers processed."
echo "  Directory structure now contains:"
echo ""
find "$ARTIFACT_ROOT" -maxdepth 2 -type f -name "forge-installer.jar"
echo "====================================================="
