#!/usr/bin/env bash
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_AVAILABLE_PATH/config/functions"
source "$PLUGIN_AVAILABLE_PATH/scheduler-docker-local/internal-functions"

fn-scheduler-docker-local-copy-from-image() {
  declare APP="$1" IMAGE_NAME="$2" CHECKS_PATH="$3"

  mkdir -p "${DOKKU_LIB_ROOT}/data/scheduler-docker-local/$APP"
  find "${DOKKU_LIB_ROOT}/data/scheduler-docker-local/$APP/" -maxdepth 1 -type f -name 'CHECKS.*' -delete
  copy_from_image "$IMAGE_NAME" "$CHECKS_PATH" "${DOKKU_LIB_ROOT}/data/scheduler-docker-local/$APP/CHECKS.$DOKKU_PID" 2>/dev/null || true
  if [[ ! -f "${DOKKU_LIB_ROOT}/data/scheduler-docker-local/$APP/CHECKS.$DOKKU_PID" ]]; then
    touch "${DOKKU_LIB_ROOT}/data/scheduler-docker-local/$APP/CHECKS.$DOKKU_PID.missing"
  fi
}

fn-scheduler-docker-local-copy-from-directory() {
  declare APP="$1" SOURCECODE_WORK_DIR="$2" CHECKS_PATH="$3"

  pushd "$SOURCECODE_WORK_DIR" >/dev/null
  mkdir -p "${DOKKU_LIB_ROOT}/data/scheduler-docker-local/$APP"

  if [[ -z "$CHECKS_PATH" ]]; then
    touch "${DOKKU_LIB_ROOT}/data/scheduler-docker-local/$APP/CHECKS.$DOKKU_PID.missing"
    return
  fi

  if [[ ! -f "$CHECKS_PATH" ]]; then
    touch "${DOKKU_LIB_ROOT}/data/scheduler-docker-local/$APP/CHECKS.$DOKKU_PID.missing"
    return
  fi

  find "${DOKKU_LIB_ROOT}/data/scheduler-docker-local/$APP/" -maxdepth 1 -type f -name 'CHECKS.*' -delete
  cp -f "$CHECKS_PATH" "${DOKKU_LIB_ROOT}/data/scheduler-docker-local/$APP/CHECKS.$DOKKU_PID"
  popd &>/dev/null || pushd "/tmp" >/dev/null
}

trigger-scheduler-docker-local-core-post-extract() {
  declare desc="scheduler-docker-local post-extract plugin trigger"
  declare trigger="post-extract"
  declare APP="$1" SOURCECODE_WORK_DIR="$2"
  local CHECKS_PATH="CHECKS" CHECKS_FILENAME="${DOKKU_LIB_ROOT}/data/scheduler-docker-local/$APP/CHECKS.$DOKKU_PID"
  local app_source_image

  app_source_image="$(plugn trigger git-get-property "$APP" "source-image")"
  if [[ -n "$app_source_image" ]]; then
    fn-scheduler-docker-local-copy-from-image "$APP" "$app_source_image" "$CHECKS_PATH"
  else
    fn-scheduler-docker-local-copy-from-directory "$APP" "$SOURCECODE_WORK_DIR" "$CHECKS_PATH"
  fi

  if [[ -f "$CHECKS_FILENAME" ]]; then
    local TMP_CHECKS_FILE=$(mktemp "/tmp/dokku-${DOKKU_PID}-${FUNCNAME[0]}.XXXXXX")
    trap "rm -rf '$TMP_CHECKS_FILE' >/dev/null" RETURN INT TERM EXIT

    template_checks() {
      declare desc="templates out the checks file"
      declare APP="$1" CHECKS_FILENAME="$2"
      eval "$(config_export app "$APP" --format exports --merged)"
      sigil -f "$CHECKS_FILENAME" | cat -s >"$TMP_CHECKS_FILE"
      mv "$TMP_CHECKS_FILE" "$CHECKS_FILENAME"
    }

    template_checks "$APP" "$CHECKS_FILENAME"
  fi
}

trigger-scheduler-docker-local-core-post-extract "$@"
