#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$(dirname "$(dirname "${BASH_SOURCE[0]}")")/functions"

cmd-google-auth-undeny() {
  declare desc="remove an address from a deny list"
  local cmd="google-auth:undeny"
  [[ "$1" == "$cmd" ]] && shift 1

  fn-ga-resolve-scope "$cmd" "${1:-}"
  local scope="$GA_SCOPE"
  shift 1 || true

  [[ $# -gt 0 ]] || dokku_log_fail "usage: dokku $cmd <app>|--global <address...>"

  local entry
  for entry in "$@"; do
    entry="${entry,,}"
    if ! fn-ga-list-contains "$scope" denied-emails "$entry"; then
      dokku_log_warn "$entry was not on the deny list $(fn-ga-scope-label "$scope")"
      # A global denial cannot be lifted per app; say so rather than let the
      # operator think the address is unblocked now.
      if [[ "$scope" != "global" ]] && fn-ga-list-contains global denied-emails "$entry"; then
        dokku_log_warn "$entry is denied globally, which no app can override — run: dokku google-auth:undeny --global $entry"
      fi
      continue
    fi
    fn-ga-list-remove "$scope" denied-emails "$entry"
    dokku_log_info1 "removed from the deny list $(fn-ga-scope-label "$scope"): $entry"
    if [[ "$scope" != "global" ]] && fn-ga-list-contains global denied-emails "$entry"; then
      dokku_log_warn "$entry is still denied globally — run: dokku google-auth:undeny --global $entry"
      continue
    fi
    # Undenying only lifts the block; the allow lists still decide.
    if ! fn-ga-email-effectively-allowed "$scope" "$entry"; then
      dokku_log_warn "$entry still cannot sign in — nothing on the allow list covers it (see: dokku google-auth:allow $(fn-ga-scope-arg "$scope"))"
    fi
  done

  fn-ga-apply-list-change "$scope"
}

cmd-google-auth-undeny "$@"
