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

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

  verify_app_name "$APP"
  local PROCTYPES="${2:-_all_}"
  local DOKKU_CHECKS_DISABLED=$(config_get "$APP" DOKKU_CHECKS_DISABLED || true)
  local DOKKU_CHECKS_SKIPPED=$(config_get "$APP" DOKKU_CHECKS_SKIPPED || true)

  if [[ "$PROCTYPES" == "_all_" ]]; then
    dokku_log_info1 "Skipping zero downtime for app ($APP)"
    DOKKU_QUIET_OUTPUT=1 config_set --no-restart "$APP" DOKKU_CHECKS_SKIPPED="$PROCTYPES"
    DOKKU_QUIET_OUTPUT=1 config_unset --no-restart "$APP" DOKKU_CHECKS_DISABLED
  else
    dokku_log_info1 "Skipping zero downtime for app's ($APP) proctypes ($PROCTYPES)"
    local PROCTYPE OIFS="$IFS" IFS=,
    for PROCTYPE in $PROCTYPES; do
      IFS="$OIFS"
      [[ "$(is_val_in_list "$PROCTYPE" "$DOKKU_CHECKS_SKIPPED")" == "false" ]] \
        && DOKKU_CHECKS_SKIPPED="$(add_val_to_list "$PROCTYPE" "$DOKKU_CHECKS_SKIPPED")"
      [[ "$(is_val_in_list "$PROCTYPE" "$DOKKU_CHECKS_DISABLED")" == "true" ]] \
        && DOKKU_CHECKS_DISABLED="$(remove_val_from_list "$PROCTYPE" "$DOKKU_CHECKS_DISABLED")"
    done
    DOKKU_CHECKS_SKIPPED="$(remove_val_from_list "_all_" "$DOKKU_CHECKS_SKIPPED")"
    if [[ -z "$DOKKU_CHECKS_DISABLED" ]]; then
      DOKKU_QUIET_OUTPUT=1 config_unset --no-restart "$APP" DOKKU_CHECKS_DISABLED
    else
      DOKKU_QUIET_OUTPUT=1 config_set --no-restart "$APP" DOKKU_CHECKS_DISABLED="$DOKKU_CHECKS_DISABLED"
    fi

    if [[ -z "$DOKKU_CHECKS_SKIPPED" ]]; then
      DOKKU_QUIET_OUTPUT=1 config_unset --no-restart "$APP" DOKKU_CHECKS_SKIPPED
    else
      DOKKU_QUIET_OUTPUT=1 config_set --no-restart "$APP" DOKKU_CHECKS_SKIPPED="$DOKKU_CHECKS_SKIPPED"
    fi
  fi
}

cmd-checks-skip "$@"
