#!/bin/bash
#
# Зеркальная синхронизация ./datapacks → ./saves/$LOCAL_WORLD/datapacks
# LOCAL_WORLD берётся из .env (см. .env.example).
#
# Использование:
#   bash/sync-datapacks-to-world.sh          # один раз
#   bash/sync-datapacks-to-world.sh --watch  # следить за изменениями
#
set -euo pipefail

SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)
REPO_ROOT="${SCRIPT_DIR}/.."
ENV_FILE="${REPO_ROOT}/.env"
DATAPACKS_SRC="${REPO_ROOT}/datapacks/"

if [[ -f "${ENV_FILE}" ]]; then
    set -a
    # shellcheck disable=SC1090
    source "${ENV_FILE}"
    set +a
fi

LOCAL_WORLD="${LOCAL_WORLD:-Новый мир}"
DATAPACKS_DST="${REPO_ROOT}/saves/${LOCAL_WORLD}/datapacks/"

sync_once() {
    if [[ ! -d "${DATAPACKS_SRC}" ]]; then
        echo "Ошибка: не найдена папка ${DATAPACKS_SRC}"
        exit 1
    fi

    mkdir -p "${DATAPACKS_DST}"
    echo "[$(date '+%H:%M:%S')] ${DATAPACKS_SRC} → ${DATAPACKS_DST}"
    rsync -a --delete "${DATAPACKS_SRC}" "${DATAPACKS_DST}"
    echo "[$(date '+%H:%M:%S')] готово"
}

watch_mode() {
    if ! command -v inotifywait &> /dev/null; then
        echo "Ошибка: inotifywait не найден (пакет inotify-tools)"
        exit 1
    fi

    sync_once
    echo "Watching ${DATAPACKS_SRC} for changes..."

    while inotifywait -r -e modify,create,delete,move "${DATAPACKS_SRC}" &> /dev/null; do
        sync_once
    done
}

case "${1:-}" in
    --watch|-w)
        watch_mode
        ;;
    --help|-h)
        echo "Usage: $(basename "$0") [--watch]"
        ;;
    "")
        sync_once
        ;;
    *)
        echo "Неизвестный аргумент: $1"
        exit 1
        ;;
esac
