#!/usr/bin/env bash

log() {
  printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*"
}

fail() {
  printf 'ERROR: %s\n' "$*" >&2
  exit 1
}

run_step() {
  local message="$1"
  shift
  log "$message"
  "$@"
}

require_root() {
  [[ "${EUID}" -eq 0 ]] || fail "Ten skrypt musi byc uruchomiony jako root."
}

require_file() {
  local path="$1"
  [[ -f "$path" ]] || fail "Brak wymaganego pliku: $path"
}

require_dir() {
  local path="$1"
  [[ -d "$path" ]] || fail "Brak wymaganego katalogu: $path"
}

set_key_value() {
  local path="$1"
  local key="$2"
  local value="$3"

  touch "$path"
  if grep -qE "^${key}=" "$path"; then
    sed -i -E "s|^${key}=.*|${key}=${value}|" "$path"
  else
    printf '%s=%s\n' "$key" "$value" >> "$path"
  fi
}

get_key_value() {
  local path="$1"
  local key="$2"
  local value

  value="$(grep -m1 -E "^${key}=" "$path" | cut -d= -f2-)"
  [[ -n "$value" ]] || fail "Brak wartosci $key w $path"
  printf '%s\n' "$value"
}

get_optional_key_value() {
  local path="$1"
  local key="$2"

  grep -m1 -E "^${key}=" "$path" | cut -d= -f2- || true
}

get_php_release_list() {
  local path="$1"
  local value
  local first=1
  local idx

  for idx in 1 2 3 4 5 6 7 8 9; do
    value="$(get_optional_key_value "$path" "php${idx}_release")"
    [[ -n "$value" && "$value" != "no" ]] || continue

    if [[ "$first" -eq 1 ]]; then
      printf 'PHP %s (domyślna)' "$value"
      first=0
    else
      printf '\nPHP %s' "$value"
    fi
  done
}

render_template() {
  local template="$1"
  local output="$2"

  perl -pe 's/\{\{([A-Z0-9_]+)\}\}/exists $ENV{$1} ? $ENV{$1} : $&/ge' "$template" > "$output"
}
