#!/bin/bash

# ==============================================================
#                    УСТАНОВКА ПЕРЕМЕННЫХ
# ==============================================================
MODS_DIR="/var/www/ftp.bocchicraft.ru/mods"
CONFIGS_DIR="/var/www/ftp.bocchicraft.ru/configs"
CLIENT_FILE="/var/www/ftp.bocchicraft.ru/client/client.zip"

MODS_LIST_FILE="/var/www/ftp.bocchicraft.ru/jsons/mods_list.json"
CONFIGS_LIST_FILE="/var/www/ftp.bocchicraft.ru/jsons/configs_list.json"
SIZES_FILE="/var/www/ftp.bocchicraft.ru/jsons/sizes.json"
CHANGES_FILE="/var/www/ftp.bocchicraft.ru/jsons/changes.json"


# ==============================================================
#                    ПЕРЕМЕЩЕНИЕ СТАРЫХ JSON
# ==============================================================

backup_if_exists() {
  local file="$1"
  if [ -f "$file" ]; then
    cp "$file" "$(dirname "$file")/old-$(basename "$file")"
  fi
}

backup_if_exists "$MODS_LIST_FILE"
backup_if_exists "$CONFIGS_LIST_FILE"


# ============================================================== 
#                   ГЕНЕРАЦИЯ MODS_LIST.JSON (с хэшами)
# ==============================================================

if [ ! -d "$MODS_DIR" ]; then
  echo "Папка $MODS_DIR не найдена!"
  exit 1
fi

echo "[" > "$MODS_LIST_FILE"

first=1
find "$MODS_DIR" -type f -name "*.jar" | while read -r file; do
    rel_path="${file#$MODS_DIR/}"
    hash=$(sha256sum "$file" | awk '{print $1}')

    if [ $first -eq 0 ]; then
        echo "," >> "$MODS_LIST_FILE"
    else
        first=0
    fi

    echo "  { \"file\": \"$rel_path\", \"hash\": \"$hash\" }" >> "$MODS_LIST_FILE"
done

echo "" >> "$MODS_LIST_FILE"
echo "]" >> "$MODS_LIST_FILE"

echo "Список модов с хэшами сохранён в $MODS_LIST_FILE"


# ============================================================== 
#                   ГЕНЕРАЦИЯ CONFIGS_LIST.JSON (с хэшами)
# ==============================================================

if [ ! -d "$CONFIGS_DIR" ]; then
  echo "Папка $CONFIGS_DIR не найдена!"
  exit 1
fi

echo "[" > "$CONFIGS_LIST_FILE"

first=1
find "$CONFIGS_DIR" -type f -name "*.cfg" | while read -r file; do
    rel_path="${file#$CONFIGS_DIR/}"
    hash=$(sha256sum "$file" | awk '{print $1}')

    if [ $first -eq 0 ]; then
        echo "," >> "$CONFIGS_LIST_FILE"
    else
        first=0
    fi

    echo "  { \"file\": \"$rel_path\", \"hash\": \"$hash\" }" >> "$CONFIGS_LIST_FILE"
done

echo "" >> "$CONFIGS_LIST_FILE"
echo "]" >> "$CONFIGS_LIST_FILE"

echo "Список конфигов с хэшами сохранён в $CONFIGS_LIST_FILE"


# ==============================================================
#                   ГЕНЕРАЦИЯ CHANGES.JSON
# ==============================================================

generate_changes() {
  local old_file="$1"
  local new_file="$2"
  declare -A old_map
  declare -A new_map
  local changes=()

  # --- Заполняем old_map ---
  if [ -f "$old_file" ]; then
    while read -r line; do
      file=$(echo "$line" | jq -r '.file')
      hash=$(echo "$line" | jq -r '.hash')
      old_map["$file"]="$hash"
    done < <(jq -c '.[]' "$old_file")
  fi

  # --- Заполняем new_map ---
  if [ -f "$new_file" ]; then
    while read -r line; do
      file=$(echo "$line" | jq -r '.file')
      hash=$(echo "$line" | jq -r '.hash')
      new_map["$file"]="$hash"
    done < <(jq -c '.[]' "$new_file")
  fi

  # --- Добавленные и обновленные файлы ---
  for f in "${!new_map[@]}"; do
    if [ -z "${old_map[$f]}" ]; then
      changes+=("add $f")
    elif [ "${old_map[$f]}" != "${new_map[$f]}" ]; then
      changes+=("update $f")
    fi
  done

  # --- Удаленные файлы ---
  for f in "${!old_map[@]}"; do
    if [ -z "${new_map[$f]}" ]; then
      changes+=("remove $f")
    fi
  done

  # --- Генерация JSON ---
  local CURRENT_DATE
  CURRENT_DATE=$(date +"%Y-%m-%d %H:%M:%S")

  {
    echo "{"
    echo "  \"date\": \"$CURRENT_DATE\","
    echo "  \"text\": \"$(IFS=' + '; echo "${changes[*]}")\""
    echo "}"
  } > "$CHANGES_FILE"
}

# --- Вызов функции для модов и конфигов ---
generate_changes "$(dirname "$MODS_LIST_FILE")/old-$(basename "$MODS_LIST_FILE")" "$MODS_LIST_FILE"
generate_changes "$(dirname "$CONFIGS_LIST_FILE")/old-$(basename "$CONFIGS_LIST_FILE")" "$CONFIGS_LIST_FILE"

echo "Файл изменений сохранён в $CHANGES_FILE"
