#!/usr/bin/env bash
set -euo pipefail
GOG_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
source "${GOG_DIR}/config.sh"
# shellcheck source=wine-fonts.sh
source "${GOG_DIR}/wine-fonts.sh"

CACHE="${GAMES_CACHE_DIR}/corefonts"
FONTS="${BOTTLE_DIR}/drive_c/windows/Fonts"

cmd_fetch() {
  local name="$1" url="$2"
  mkdir -p "${CACHE}"
  if [[ -f "${CACHE}/${name}" ]] && [[ "$(wc -c <"${CACHE}/${name}")" -gt 10000 ]]; then
    return 0
  fi
  echo "Скачиваю ${name}…"
  curl -fsSL --retry 3 -o "${CACHE}/${name}" "${url}" || return 1
}

cmd_extract_cab() {
  local cab="$1" out="${CACHE}/extract-${2:-x}"
  rm -rf "${out}"
  mkdir -p "${out}"
  cabextract -d "${out}" "${cab}"
  find "${out}" -iname '*.ttf' -exec cp -n {} "${FONTS}/" \;
}

gog_wine_check
command -v cabextract >/dev/null || { echo "brew install cabextract"; exit 1; }
mkdir -p "${FONTS}" "${CACHE}"

cmd_fetch andale32.exe "https://downloads.sourceforge.net/corefonts/andale32.exe" \
  || cmd_fetch andale32.exe "https://ftp.debian.org/debian/pool/contrib/m/msttcorefonts/andale32.exe" || true
cmd_fetch arial32.exe "https://downloads.sourceforge.net/corefonts/arial32.exe" \
  || cmd_fetch arial32.exe "https://ftp.debian.org/debian/pool/contrib/m/msttcorefonts/arial32.exe" || true
cmd_fetch times32.exe "https://downloads.sourceforge.net/corefonts/times32.exe" \
  || cmd_fetch times32.exe "https://ftp.debian.org/debian/pool/contrib/m/msttcorefonts/times32.exe" || true

for cab in andale32.exe arial32.exe times32.exe; do
  [[ -f "${CACHE}/${cab}" ]] && [[ "$(wc -c <"${CACHE}/${cab}")" -gt 10000 ]] \
    && cmd_extract_cab "${CACHE}/${cab}" "${cab%.exe}" || true
done

gog_wine_ensure_fonts 1
touch "${BOTTLE_DIR}/.gog_corefonts_installed"
echo "OK: corefonts в GOG bottle ($(ls "${FONTS}" | wc -l | tr -d ' ') файлов)"
