#!/bin/bash
set -o errexit
set -o nounset
set -o pipefail
set -x

_prepare_pack_dirs() {
  mkdir -p dist replay
}

_apply_locale_overlay() {
  cp -rf "locales/$TARGET_LOCALE/"* .
}

_collect_existing_files() {
  local existing=()
  local path
  for path in "$@"; do
    if [[ -e "$path" ]]; then
      existing+=("$path")
    fi
  done

  printf '%s\n' "${existing[@]}"
}

_append_files() {
  local array_name="$1"
  shift
  local value
  for value in "$@"; do
    eval "$array_name+=(\"\$value\")"
  done
}

_remove_files() {
  local array_name="$1"
  shift
  local removals=("$@")
  local filtered=()
  local value
  local removal
  local skip

  eval "local current=(\"\${${array_name}[@]}\")"
  for value in "${current[@]}"; do
    skip=0
    for removal in "${removals[@]}"; do
      if [[ "$value" == "$removal" ]]; then
        skip=1
        break
      fi
    done
    if [[ "$skip" -eq 0 ]]; then
      filtered+=("$value")
    fi
  done

  eval "$array_name=(\"\${filtered[@]}\")"
}

_pack_tar_archive() {
  local archive_name="$1"
  shift

  local files
  _prepare_pack_dirs
  mapfile -t files < <(_collect_existing_files "$@")
  tar -acf "dist/${archive_name}" --exclude='.git*' "${files[@]}"
}

_get_cpu_count() {
  local cpu_count
  cpu_count=$(nproc 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)
  if [[ ! "$cpu_count" =~ ^[0-9]+$ || "$cpu_count" -lt 1 ]]; then
    cpu_count=1
  fi

  echo "$cpu_count"
}

_get_memory_limit_kib() {
  local mem_total_kib
  mem_total_kib=$(awk '/MemTotal:/ {print $2}' /proc/meminfo)

  local limit_kib="$mem_total_kib"
  local cgroup_limit
  local cgroup_limit_kib
  if [[ -r /sys/fs/cgroup/memory.max ]]; then
    cgroup_limit=$(cat /sys/fs/cgroup/memory.max)
    if [[ "$cgroup_limit" != "max" && "$cgroup_limit" =~ ^[0-9]+$ ]]; then
      cgroup_limit_kib=$((cgroup_limit / 1024))
      if (( cgroup_limit_kib > 0 && cgroup_limit_kib < limit_kib )); then
        limit_kib="$cgroup_limit_kib"
      fi
    fi
  elif [[ -r /sys/fs/cgroup/memory/memory.limit_in_bytes ]]; then
    cgroup_limit=$(cat /sys/fs/cgroup/memory/memory.limit_in_bytes)
    if [[ "$cgroup_limit" =~ ^[0-9]+$ ]]; then
      cgroup_limit_kib=$((cgroup_limit / 1024))
      if (( cgroup_limit_kib > 0 && cgroup_limit_kib < limit_kib )); then
        limit_kib="$cgroup_limit_kib"
      fi
    fi
  fi

  echo "$limit_kib"
}

_parse_7z_dict_mib() {
  local value="${1,,}"
  local number
  local unit
  if [[ ! "$value" =~ ^([0-9]+)([kmg]?)b?$ ]]; then
    return 1
  fi

  number="${BASH_REMATCH[1]}"
  unit="${BASH_REMATCH[2]}"
  case "$unit" in
    k)
      echo $(((number + 1023) / 1024))
      ;;
    g)
      echo $((number * 1024))
      ;;
    *)
      echo "$number"
      ;;
  esac
}

_estimate_7z_memory_kib() {
  local threads="$1"
  local dict_mib="$2"

  echo $(((128 + threads * dict_mib * 12) * 1024))
}

_choose_7z_settings() {
  local cpu_count
  local memory_limit_kib
  local memory_budget_kib
  local max_threads
  local threads
  local dict_mib
  local estimated_kib
  local dict_candidates=(64 32 16 8)

  cpu_count=$(_get_cpu_count)
  max_threads=$((cpu_count / 2))
  if (( max_threads < 1 )); then
    max_threads=1
  fi

  threads="$max_threads"
  if [[ -n "${PACK_7Z_THREADS:-}" ]]; then
    if [[ ! "$PACK_7Z_THREADS" =~ ^[0-9]+$ || "$PACK_7Z_THREADS" -lt 1 ]]; then
      echo "Invalid PACK_7Z_THREADS: $PACK_7Z_THREADS" >&2
      exit 1
    fi
    threads="$PACK_7Z_THREADS"
    if (( threads > max_threads )); then
      echo "Capping PACK_7Z_THREADS=${threads} to half of available CPUs: ${max_threads}" >&2
      threads="$max_threads"
    fi
  fi

  memory_limit_kib=$(_get_memory_limit_kib)
  memory_budget_kib=$((memory_limit_kib / 2))

  if [[ -n "${PACK_7Z_DICT_SIZE:-}" ]]; then
    dict_mib=$(_parse_7z_dict_mib "$PACK_7Z_DICT_SIZE") || {
      echo "Invalid PACK_7Z_DICT_SIZE: $PACK_7Z_DICT_SIZE" >&2
      exit 1
    }
    while (( threads > 1 )); do
      estimated_kib=$(_estimate_7z_memory_kib "$threads" "$dict_mib")
      if (( estimated_kib <= memory_budget_kib )); then
        break
      fi
      threads=$((threads - 1))
    done

    estimated_kib=$(_estimate_7z_memory_kib "$threads" "$dict_mib")
    if (( estimated_kib > memory_budget_kib )); then
      echo "PACK_7Z_DICT_SIZE=${PACK_7Z_DICT_SIZE} does not fit in half of available memory" >&2
      exit 1
    fi

    printf '%s %sm\n' "$threads" "$dict_mib"
    return
  fi

  while true; do
    for dict_mib in "${dict_candidates[@]}"; do
      estimated_kib=$(_estimate_7z_memory_kib "$threads" "$dict_mib")
      if (( estimated_kib <= memory_budget_kib )); then
        printf '%s %sm\n' "$threads" "$dict_mib"
        return
      fi
    done

    if (( threads <= 1 )); then
      printf '1 8m\n'
      return
    fi
    threads=$((threads - 1))
  done
}

_pack_7z_archive() {
  local archive_name="$1"
  shift

  local files
  local dict_size
  local threads

  _prepare_pack_dirs
  mapfile -t files < <(_collect_existing_files "$@")
  read -r threads dict_size < <(_choose_7z_settings)
  echo "Running 7z with -mx9, -md=${dict_size}, -mmt=${threads}"
  7z a -m0=lzma2 -mx9 "-md=${dict_size}" "-mmt=${threads}" -xr!.git* "dist/${archive_name}" "${files[@]}"
}

_append_base_files() {
  local array_name="$1"
  _append_files "$array_name" \
    strings.conf system.conf servers.conf \
    cards.cdb textures locales fonts pack skin
}

_append_dlc_files() {
  local array_name="$1"
  _append_base_files "$array_name"
  _append_files "$array_name" sound
}

_append_release_files() {
  local array_name="$1"
  _append_dlc_files "$array_name"
  _append_files "$array_name" \
    LICENSE README.md lflist.conf \
    script deck single pics replay bot.conf
}

_append_win_locale_updater() {
  local array_name="$1"
  local archive_kind="$2"
  if [[ "$TARGET_LOCALE" != "zh-CN" ]]; then
    return
  fi

  if [[ "$archive_kind" == "7z" || "$ARCHIVE_SUFFIX" != "zst" ]]; then
    _append_files "$array_name" update-koishipro
  fi
}

_append_platform_files() {
  local array_name="$1"
  local package_kind="$2"
  local target_platform="$3"

  case "$target_platform" in
    darwin)
      _append_files "$array_name" ygopro.app
      if [[ "$package_kind" == "release" ]]; then
        _append_files "$array_name" windbot bot
      fi
      ;;
    linux|linuxarm)
      _append_files "$array_name" ygopro
      if [[ "$package_kind" == "release" ]]; then
        _append_files "$array_name" windbot bot
      fi
      ;;
    win32)
      _append_files "$array_name" ygopro.exe vcomp140.dll
      if [[ "$package_kind" == "release" ]]; then
        _append_files "$array_name" Bot.exe WindBot
      fi
      ;;
    *)
      echo "Unsupported platform: $target_platform" >&2
      exit 1
      ;;
  esac
}

_pack_release() {
  local default_platform="$1"
  local target_platform="${TARGET_PLATFORM:-$default_platform}"
  local archive_name="KoishiPro-${CI_COMMIT_REF_NAME}-${target_platform}-${TARGET_LOCALE}.tar.${ARCHIVE_SUFFIX}"
  local files=()

  _append_release_files files
  _append_platform_files files release "$target_platform"
  _append_win_locale_updater files tar

  _pack_tar_archive "$archive_name" "${files[@]}"
}

_pack_dlc() {
  local default_platform="$1"
  local target_platform="${TARGET_PLATFORM:-$default_platform}"
  local archive_name="KoishiPro-dlc-${CI_COMMIT_REF_NAME}-${target_platform}-${TARGET_LOCALE}.tar.${ARCHIVE_SUFFIX}"
  local files=()

  _apply_locale_overlay
  _append_dlc_files files
  _append_platform_files files dlc "$target_platform"

  _pack_tar_archive "$archive_name" "${files[@]}"
}

_pack_7z() {
  local target_platform="${TARGET_PLATFORM:-win32}"
  local archive_name="KoishiPro-${CI_COMMIT_REF_NAME}-${target_platform}-${TARGET_LOCALE}.7z"
  local files=()

  _append_release_files files
  _append_platform_files files release "$target_platform"
  _append_win_locale_updater files 7z

  _pack_7z_archive "$archive_name" "${files[@]}"
}
