#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_CORE_AVAILABLE_PATH/common/property-functions"

cmd-checks-enable() {
  declare desc="enable zero-downtime checks for app/proctypes"
  declare cmd="checks:enable"
  [[ "$1" == "$cmd" ]] && shift 1
  declare APP="$1"

  verify_app_name "$APP"
  local PROCTYPES="${2:-_all_}"

  local DOKKU_CHECKS_DISABLED=$(fn-plugin-property-get-default "checks" "$APP" "disabled" "")
  local DOKKU_CHECKS_SKIPPED=$(fn-plugin-property-get-default "checks" "$APP" "skipped" "")

  if [[ "$PROCTYPES" == "_all_" ]]; then
    dokku_log_info1 "Enabling zero downtime for app's ($APP)"
    fn-plugin-property-delete "checks" "$APP" "disabled"
    fn-plugin-property-delete "checks" "$APP" "skipped"
  else
    dokku_log_info1 "Enabling zero downtime for app's ($APP) proctypes ($PROCTYPES)"
    local PROCTYPE OIFS="$IFS" IFS=,
    for PROCTYPE in $PROCTYPES; do
      DOKKU_CHECKS_DISABLED="$(remove_val_from_list "$PROCTYPE" "$DOKKU_CHECKS_DISABLED")"
      DOKKU_CHECKS_SKIPPED="$(remove_val_from_list "$PROCTYPE" "$DOKKU_CHECKS_SKIPPED")"
    done

    IFS="$OIFS"
    if [[ -z "$DOKKU_CHECKS_DISABLED" ]]; then
      fn-plugin-property-delete "checks" "$APP" "disabled"
    else
      fn-plugin-property-write "checks" "$APP" "disabled" "$DOKKU_CHECKS_DISABLED"
    fi

    if [[ -z "$DOKKU_CHECKS_SKIPPED" ]]; then
      fn-plugin-property-delete "checks" "$APP" "skipped"
    else
      fn-plugin-property-write "checks" "$APP" "skipped" "$DOKKU_CHECKS_SKIPPED"
    fi
  fi
}

cmd-checks-enable "$@"
