#!/usr/bin/env bash
set -euo pipefail

mapfile -t PHP_INI_DIRS < <(compgen -G "/usr/local/php*/lib/php.conf.d" || true)

if [[ ${#PHP_INI_DIRS[@]} -eq 0 ]]; then
  echo "Brak katalogów /usr/local/phpXX/lib/php.conf.d do przetworzenia." >&2
  exit 1
fi

for dir in "${PHP_INI_DIRS[@]}"; do
  [[ -d "$dir" ]] || continue

  php_tag="$(basename "$(dirname "$(dirname "$dir")")")"
  num="${php_tag#php}"
  major="${num:0:1}"

  read -r -d '' OPCACHE_BLOCK <<'OPC_END' || true
[opcache]
opcache.enable=1
opcache.enable_cli=0
opcache.memory_consumption=256
opcache.interned_strings_buffer=32
opcache.max_accelerated_files=16229
opcache.max_wasted_percentage=10
opcache.revalidate_freq=10
opcache.fast_shutdown=1
opcache.enable_file_override=0
opcache.max_file_size=0
opcache.validate_timestamps=1
opcache.revalidate_path=0
OPC_END

  JIT_BLOCK=""
  if [[ "$major" -ge 8 ]]; then
    JIT_BLOCK=$'opcache.jit_buffer_size=256M\nopcache.jit=1255\n'
  fi

  target="${dir}/20-hitme.ini"
  echo "Tworzę ${target}"

  cat >"$target" <<INI
[Date]
date.timezone = Europe/Warsaw

[Session]
session.auto_start = Off

[PHP]
short_open_tag = Off
display_errors = Off

magic_quotes_gpc = off
memory_limit = 512M
max_execution_time = 1500
max_input_time = 1500
upload_max_filesize = 512M
post_max_size = 512M
max_input_vars = 100000
allow_url_fopen = on

${OPCACHE_BLOCK}
${JIT_BLOCK}
INI

done

echo "Przebudowuję konfiguracje Apache/PHP w DirectAdmin..."

if command -v da >/dev/null 2>&1; then
  da build rewrite_confs
elif [[ -x /usr/local/directadmin/custombuild/build ]]; then
  /usr/local/directadmin/custombuild/build rewrite_confs
else
  echo "Nie znaleziono polecenia build rewrite_confs" >&2
  exit 2
fi

echo "Gotowe."
