#!/usr/bin/env bash
# Packages the resource pack, computes SHA1, and updates server.properties.
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SERVER_DIR="$(dirname "$SCRIPT_DIR")"
PACK_NAME="zerolands-resourcepack.zip"
OUTPUT="$SERVER_DIR/$PACK_NAME"
PROPS="$SERVER_DIR/server.properties"

echo "=== Building resource pack ==="

# Remove previous build
rm -f "$OUTPUT"

# Zip everything inside the resourcepack folder (pack.mcmeta must be at root of zip)
cd "$SCRIPT_DIR"
zip -r "$OUTPUT" pack.mcmeta assets/ -x "*.txt" -x "build_pack.sh" -x ".DS_Store"

SHA1=$(sha1sum "$OUTPUT" | awk '{print $1}')
echo "Built: $OUTPUT"
echo "SHA1:  $SHA1"

# ─── Update server.properties in-place ───────────────────────────────────────
if [ -f "$PROPS" ]; then
    # Read current URL (preserve whatever the user set)
    CURRENT_URL=$(grep '^resource-pack=' "$PROPS" | cut -d= -f2-)

    sed -i \
        -e "s|^resource-pack-sha1=.*|resource-pack-sha1=$SHA1|" \
        "$PROPS"

    echo ""
    echo "server.properties SHA1 updated."
    if [ -z "$CURRENT_URL" ]; then
        echo ""
        echo "ACTION REQUIRED: set the resource-pack URL in server.properties:"
        echo "  resource-pack=http://<your-server-ip>:8080/$PACK_NAME"
    else
        echo "Resource pack URL: $CURRENT_URL"
    fi
fi

echo ""
echo "=== Done ==="
echo "Upload $OUTPUT to your web server (see docker-compose in resourcepack-server/)."
echo "Then restart or reload the Minecraft server."
