#!/bin/bash

# shellcheck source=start-utils
. "$(dirname "$0")/start-utils"

set -e
handleDebugMode

: "${REPLACE_ENV_IN_PLACE:=${REPLACE_ENV_VARIABLES:-false}}"
: "${REPLACE_ENV_PATHS:=/data}"
: "${REPLACE_ENV_SUFFIXES:=yml,yaml,txt,cfg,conf,properties,hjson,json,tml,toml}"
: "${REPLACE_ENV_VARIABLE_PREFIX=${ENV_VARIABLE_PREFIX:-CFG_}}"
: "${REPLACE_ENV_VARIABLES_EXCLUDES:=}"
: "${REPLACE_ENV_VARIABLES_EXCLUDE_PATHS:=}"
: "${PATCH_DEFINITIONS:=}"
: "${DEBUG:=false}"
: "${DOWNLOAD_DEFAULTS:=}"
: "${DOWNLOAD_DEFAULT_CONFIGS:=}"
: "${SKIP_DOWNLOAD_DEFAULTS:=false}"
: "${APPLY_EXTRA_FILES:=${DOWNLOAD_EXTRA_CONFIGS:-}}"

if isTrue "${REPLACE_ENV_IN_PLACE}"; then
  log "Replacing env variables in ${REPLACE_ENV_PATHS} that match the prefix '$REPLACE_ENV_VARIABLE_PREFIX' ..."

  mc-image-helper interpolate \
    --replace-env-file-suffixes="${REPLACE_ENV_SUFFIXES}" \
    --replace-env-excludes="${REPLACE_ENV_VARIABLES_EXCLUDES}" \
    --replace-env-exclude-paths="${REPLACE_ENV_VARIABLES_EXCLUDE_PATHS}" \
    --replace-env-prefix="${REPLACE_ENV_VARIABLE_PREFIX}" \
    "${REPLACE_ENV_PATHS[@]}"
fi

if isFalse "$SKIP_DOWNLOAD_DEFAULTS"; then
  commonArgs=(
    --skip-existing
    --skip-up-to-date=false
    --quiet-when-skipped
    --ignore-missing-sources
  )
  if [[ $DOWNLOAD_DEFAULT_CONFIGS ]]; then
    if ! mc-image-helper mcopy \
      --to /data/config \
      "${commonArgs[@]}" \
      "$DOWNLOAD_DEFAULT_CONFIGS"; then
      logWarning "One or more default config files were not available from $DOWNLOAD_DEFAULT_CONFIGS"
    fi
  fi
  if [[ $DOWNLOAD_DEFAULTS ]]; then
    if ! mc-image-helper mcopy \
      --to /data \
      "${commonArgs[@]}" \
      "$DOWNLOAD_DEFAULTS"; then
      logWarning "One or more default files were not available from $DOWNLOAD_DEFAULTS"
    fi
  fi
fi

if [[ $APPLY_EXTRA_FILES ]]; then
  mc-image-helper mcopy \
    --to /data \
    --skip-existing \
    --skip-up-to-date=false \
    --quiet-when-skipped \
    "$APPLY_EXTRA_FILES"
fi

if [[ ${PATCH_DEFINITIONS} ]]; then
  log "Applying patch definitions from ${PATCH_DEFINITIONS}"
  mc-image-helper patch \
    --patch-env-prefix="${REPLACE_ENV_VARIABLE_PREFIX}" \
    "${PATCH_DEFINITIONS}"
fi

exec "$(dirname "$0")/start-setupRbac" "$@"
