#!/bin/bash

with_nounset_compat() {
  local had_nounset=0
  case $- in
    *u*)
      had_nounset=1
      set +u
      ;;
  esac

  "$@"
  local rc=$?

  if [ "$had_nounset" -eq 1 ]; then
    set -u
  fi

  return "$rc"
}

source_if_exists() {
  local path="$1"
  if [ -r "$path" ]; then
    with_nounset_compat . "$path"
  fi
}

require_file() {
  local path="$1"
  if [ ! -f "$path" ]; then
    echo "Error: required file not found: $path" >&2
    exit 1
  fi
}

require_action() {
  local action="$1"
  shift

  local supported_action
  for supported_action in "$@"; do
    if [ "$action" = "$supported_action" ]; then
      return 0
    fi
  done

  echo "Error: unsupported action: $action" >&2
  exit 2
}

read_last_property_value() {
  local key="$1"
  local file="$2"
  awk -F= -v key="$key" '$1 == key { value=$0; sub(/^[^=]*=/, "", value) } END { if (value != "") print value }' "$file"
}

detect_java_home() {
  # shellcheck source=/usr/lib/bigtop-utils/bigtop-detect-javahome
  with_nounset_compat . /usr/lib/bigtop-utils/bigtop-detect-javahome
}

detect_java_home_if_unset() {
  if [ -z "${JAVA_HOME:-}" ]; then
    detect_java_home
  fi
}

export_home_from_prefix() {
  local home_var="$1"
  local prefix_var="$2"

  if [ -n "${!prefix_var:-}" ] && [ -z "${!home_var:-}" ]; then
    export "$home_var=${!prefix_var}"
  fi
  unset "$prefix_var"
}

append_colon_path_var() {
  local var_name="$1"
  local value="$2"
  local current_value="${!var_name:-}"

  if [ -z "$value" ]; then
    return 0
  fi

  if [ -n "$current_value" ]; then
    printf -v "$var_name" '%s:%s' "$current_value" "$value"
  else
    printf -v "$var_name" '%s' "$value"
  fi
  export "${var_name?}"
}

ensure_dirs() {
  local mode=0755

  if [ "${1:-}" = "-m" ]; then
    mode="$2"
    shift 2
  fi

  if [ "$#" -eq 0 ]; then
    echo "Error: ensure_dirs requires at least one path" >&2
    exit 2
  fi

  if ! install -d -m "$mode" "$@"; then
    echo "Error: failed to create directories: $*" >&2
    exit 1
  fi
}

redirect_stdout_stderr_to_file() {
  local path="$1"
  local parent

  parent="$(dirname "$path")"
  ensure_dirs "$parent"

  if ! : >> "$path"; then
    echo "Error: failed to open log file for append: $path" >&2
    exit 1
  fi

  exec >> "$path" 2>&1
}
