#!/bin/bash
set -e

# Sugma Modded Server - macOS Installation Script
# Installs Fabric Loader 0.18.4 for Minecraft 1.21.1 and all required mods

echo "================================================"
echo "  Sugma Modded Minecraft Server Installer"
echo "  macOS Version"
echo "================================================"
echo ""

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
MINECRAFT_VERSION="1.21.1"
FABRIC_LOADER_VERSION="0.18.4"
SERVER_ADDRESS="modded-minecraft.jarobinson.org"
MOD_DOWNLOAD_URL="https://modded-minecraft.jarobinson.org/mods"
MINECRAFT_DIR="$HOME/Library/Application Support/minecraft"
MODS_DIR="$MINECRAFT_DIR/mods"

# Step 1: Check for Java 21+
echo -e "${YELLOW}[1/6]${NC} Checking Java installation..."
if command -v java &> /dev/null; then
    JAVA_VERSION=$(java -version 2>&1 | head -n 1 | awk -F '"' '{print $2}' | cut -d'.' -f1)
    if [ "$JAVA_VERSION" -ge 21 ]; then
        echo -e "${GREEN}✓${NC} Java $JAVA_VERSION found"
    else
        echo -e "${RED}✗${NC} Java $JAVA_VERSION is too old (need 21+)"
        NEED_JAVA=true
    fi
else
    echo -e "${RED}✗${NC} Java not found"
    NEED_JAVA=true
fi

if [ "$NEED_JAVA" = true ]; then
    echo ""
    echo -e "${YELLOW}Installing Java 21 via Homebrew...${NC}"

    # Check for Homebrew
    if ! command -v brew &> /dev/null; then
        echo -e "${RED}Error:${NC} Homebrew not found. Please install from https://brew.sh"
        exit 1
    fi

    # Install Java
    brew install --cask temurin21
    echo -e "${GREEN}✓${NC} Java 21 installed"
fi

echo ""

# Step 2: Download Fabric Installer
echo -e "${YELLOW}[2/6]${NC} Downloading Fabric Installer..."
FABRIC_INSTALLER="/tmp/fabric-installer.jar"
curl -L -o "$FABRIC_INSTALLER" "https://maven.fabricmc.net/net/fabricmc/fabric-installer/1.0.1/fabric-installer-1.0.1.jar"
echo -e "${GREEN}✓${NC} Fabric Installer downloaded"
echo ""

# Step 3: Install Fabric Loader
echo -e "${YELLOW}[3/6]${NC} Installing Fabric Loader $FABRIC_LOADER_VERSION for Minecraft $MINECRAFT_VERSION..."
java -jar "$FABRIC_INSTALLER" client \
    -mcversion "$MINECRAFT_VERSION" \
    -loader "$FABRIC_LOADER_VERSION" \
    -dir "$MINECRAFT_DIR" \
    -noprofile

# Create launcher profile manually
LAUNCHER_PROFILES="$MINECRAFT_DIR/launcher_profiles.json"
if [ -f "$LAUNCHER_PROFILES" ]; then
    # Backup original
    cp "$LAUNCHER_PROFILES" "$LAUNCHER_PROFILES.backup"

    # Add Sugma profile using Python (more reliable than jq)
    python3 << 'EOF'
import json
import os

profiles_path = os.path.expanduser("~/Library/Application Support/minecraft/launcher_profiles.json")
with open(profiles_path, 'r') as f:
    data = json.load(f)

# Add Sugma profile
if 'profiles' not in data:
    data['profiles'] = {}

data['profiles']['sugma-modded'] = {
    "name": "Sugma Modded 1.21.1",
    "type": "custom",
    "created": "2026-01-24T00:00:00.000Z",
    "lastUsed": "2026-01-24T00:00:00.000Z",
    "icon": "Furnace",
    "lastVersionId": "fabric-loader-0.18.4-1.21.1",
    "javaArgs": "-Xmx4G -Xms2G"
}

with open(profiles_path, 'w') as f:
    json.dump(data, f, indent=2)

print("Profile created successfully")
EOF
fi

echo -e "${GREEN}✓${NC} Fabric Loader installed"
echo ""

# Step 4: Backup existing mods folder
echo -e "${YELLOW}[4/6]${NC} Preparing mods directory..."
if [ -d "$MODS_DIR" ]; then
    BACKUP_DIR="$MODS_DIR.backup.$(date +%Y%m%d_%H%M%S)"
    echo "Backing up existing mods to: $BACKUP_DIR"
    mv "$MODS_DIR" "$BACKUP_DIR"
fi

mkdir -p "$MODS_DIR"
echo -e "${GREEN}✓${NC} Mods directory ready"
echo ""

# Step 5: Download all mods
echo -e "${YELLOW}[5/6]${NC} Downloading mods from server..."
echo "This may take a few minutes depending on your internet speed..."
echo ""

# Get list of mod files
MOD_LIST=$(curl -s "$MOD_DOWNLOAD_URL/" | grep -oE 'href="[^"]+\.jar"' | sed 's/href="//;s/"$//' | grep -v '^\/' || true)

if [ -z "$MOD_LIST" ]; then
    # Fallback: try directory listing with different format
    MOD_LIST=$(curl -s "$MOD_DOWNLOAD_URL/" | grep -oE '[^">]+\.jar' | sort -u)
fi

if [ -z "$MOD_LIST" ]; then
    echo -e "${RED}Error:${NC} Could not retrieve mod list from server"
    echo "Please ensure the server is running and accessible at: $MOD_DOWNLOAD_URL"
    exit 1
fi

# Count total mods
TOTAL_MODS=$(echo "$MOD_LIST" | wc -l | tr -d ' ')
CURRENT=0

# Download each mod
echo "$MOD_LIST" | while read -r MOD_FILE; do
    CURRENT=$((CURRENT + 1))
    echo -e "  [$CURRENT/$TOTAL_MODS] Downloading: $MOD_FILE"
    curl -s -L -o "$MODS_DIR/$MOD_FILE" "$MOD_DOWNLOAD_URL/$MOD_FILE"
done

# Verify downloads
DOWNLOADED_COUNT=$(ls "$MODS_DIR"/*.jar 2>/dev/null | wc -l | tr -d ' ')
echo ""
echo -e "${GREEN}✓${NC} Downloaded $DOWNLOADED_COUNT mods"
echo ""

# Step 6: Finish
echo -e "${YELLOW}[6/6]${NC} Installation complete!"
echo ""
echo "================================================"
echo -e "${GREEN}  Installation Successful!${NC}"
echo "================================================"
echo ""
echo "Next steps:"
echo "  1. Launch Minecraft"
echo "  2. Select profile: 'Sugma Modded 1.21.1'"
echo "  3. Click 'Play'"
echo "  4. Add server: $SERVER_ADDRESS"
echo "  5. Join and enjoy!"
echo ""
echo "Installed components:"
echo "  - Minecraft: $MINECRAFT_VERSION"
echo "  - Fabric Loader: $FABRIC_LOADER_VERSION"
echo "  - Mods: $DOWNLOADED_COUNT"
echo ""
echo "Troubleshooting:"
echo "  - If game won't launch, allocate more RAM in launcher settings"
echo "  - Recommended: 4-6GB RAM (-Xmx4G or -Xmx6G in JVM arguments)"
echo "  - Read SUGMA_SERVER_GUIDE.md for full documentation"
echo ""
echo "Server: $SERVER_ADDRESS"
echo ""

# Cleanup
rm -f "$FABRIC_INSTALLER"
