#!/bin/bash
#
# Развёртывание минимального локального тестового сервера:
# eula.txt, server.properties, start.sh + Fabric Server Launcher.
#
set -euo pipefail

SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)
REPO_ROOT="${SCRIPT_DIR}/.."
TEMPLATE_DIR="${REPO_ROOT}/server-template"
TARGET_DIR="/home/dimti/Seafile/minecraft/installers/m2612"
LOCK_FILE="${REPO_ROOT}/pakku-lock.json"
FABRIC_INSTALLER_VERSION="${FABRIC_INSTALLER_VERSION:-1.1.1}"

cd "${REPO_ROOT}" || exit 1

if [[ ! -f "${LOCK_FILE}" ]]; then
    echo "Ошибка: не найден ${LOCK_FILE}"
    exit 1
fi

MC_VERSION=$(python3 -c "import json; print(json.load(open('${LOCK_FILE}'))['mc_versions'][0])")
LOADER_VERSION=$(python3 -c "import json; print(json.load(open('${LOCK_FILE}'))['loaders']['fabric'])")
FABRIC_JAR="fabric-server-mc.${MC_VERSION}-loader.${LOADER_VERSION}-launcher.${FABRIC_INSTALLER_VERSION}.jar"
FABRIC_URL="https://meta.fabricmc.net/v2/versions/loader/${MC_VERSION}/${LOADER_VERSION}/${FABRIC_INSTALLER_VERSION}/server/jar"

echo "MC=${MC_VERSION} loader=${LOADER_VERSION} installer=${FABRIC_INSTALLER_VERSION}"
echo "Целевая папка: ${TARGET_DIR}"

mkdir -p "${TARGET_DIR}"

cp -f "${TEMPLATE_DIR}/eula.txt" "${TARGET_DIR}/eula.txt"

if [[ ! -f "${TARGET_DIR}/server.properties" ]]; then
    cp "${TEMPLATE_DIR}/server.properties" "${TARGET_DIR}/server.properties"
    echo "Создан server.properties из шаблона"
else
    echo "server.properties уже есть — не перезаписываю"
fi

sed "s/__FABRIC_SERVER_JAR__/${FABRIC_JAR}/" "${TEMPLATE_DIR}/start.sh" > "${TARGET_DIR}/start.sh"
chmod +x "${TARGET_DIR}/start.sh"
echo "Обновлён start.sh → ${FABRIC_JAR}"

if [[ -f "${TARGET_DIR}/${FABRIC_JAR}" ]]; then
    echo "Fabric launcher уже скачан: ${FABRIC_JAR}"
else
    echo "Скачиваю Fabric Server Launcher..."
    curl -fL --progress-bar -o "${TARGET_DIR}/${FABRIC_JAR}" "${FABRIC_URL}"
    echo "Скачан: ${TARGET_DIR}/${FABRIC_JAR}"
fi

echo "Готово. Запуск: ${TARGET_DIR}/start.sh"
