#!/bin/bash
set -e

cd /home/container

echo "Installing Blockland..."

curl -fsSL -A "blocklandWIN/2.0" \
    -o /tmp/latest-manifest.dat \
    http://update.blockland.us/latestVersion.php

download_url=$(head -n 1 /tmp/latest-manifest.dat | cut -f 2)

tail -n +2 /tmp/latest-manifest.dat | tr '\r\n\t' '\0' | \
xargs -0 -n 2 -P "${BL_INST_NUM_PROC:-4}" sh -c '
file="./$2"
curl -fsSL -A "blocklandWIN/2.0" --create-dirs -o "$file" "$1/$3"
' _ "$download_url"

if [[ "${BL_PATCH_ENABLE:-0}" -eq 1 ]]; then
    /usr/local/bin/patch-bl
fi

if [ "${BL_UNZIP_ADDONS:-0}" -eq 1 ]; then
    echo "Processing Add-Ons zips..."

    cd /home/container/Add-Ons || exit 1

    for zip in *.zip; do
        [ -f "$zip" ] || continue

        addon_name="${zip%.zip}"

        echo "Extracting $zip..."

        # Extract into a temp directory first
        mkdir -p "__tmp_extract__"
        unzip -o "$zip" -d "__tmp_extract__" >/dev/null

        # Count top-level items in extraction
        item_count=$(find "__tmp_extract__" -mindepth 1 -maxdepth 1 | wc -l)

        if [ "$item_count" -eq 1 ]; then
            first_item=$(find "__tmp_extract__" -mindepth 1 -maxdepth 1)

            if [ -d "$first_item" ]; then
                # Proper folder structure, just move it
                mv "$first_item" .
            else
                # Single loose file — fix structure
                mkdir -p "$addon_name"
                mv "$first_item" "$addon_name"/
            fi
        else
            # Multiple loose files — put them in folder
            mkdir -p "$addon_name"
            mv "__tmp_extract__"/* "$addon_name"/
        fi

        rm -rf "__tmp_extract__"
        rm -f "$zip"
    done
fi