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

cmd-google-auth-deny() {
  declare desc="block an address even if the allow list covers it"
  local cmd="google-auth:deny"
  [[ "$1" == "$cmd" ]] && shift 1

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

  if [[ $# -eq 0 ]]; then
    dokku_log_info2 "google-auth deny list ($(fn-ga-scope-label "$scope"))"
    local listed found=false
    while IFS= read -r listed; do
      [[ -z "$listed" ]] && continue
      dokku_log_verbose "$listed"
      found=true
    done < <(fn-ga-list-get "$scope" denied-emails)
    [[ "$found" == "false" ]] && dokku_log_verbose "(empty)"
    if [[ "$scope" != "global" ]]; then
      while IFS= read -r listed; do
        [[ -z "$listed" ]] && continue
        dokku_log_verbose "$listed (global)"
      done < <(fn-ga-list-get global denied-emails)
    fi
    return 0
  fi

  local entry
  for entry in "$@"; do
    fn-ga-validate-list-entry "$entry" ||
      dokku_log_fail "invalid entry '$entry' — use a full address (former@signal.org), with no spaces or commas"
    entry="${entry,,}"
    [[ "$entry" == *@* ]] ||
      dokku_log_fail "google-auth:deny takes a full address, not a domain; to stop allowing all of '$entry', run: dokku google-auth:unallow $(fn-ga-scope-arg "$scope") $entry"
    fn-ga-list-add "$scope" denied-emails "$entry"
    dokku_log_info1 "denied $(fn-ga-scope-label "$scope"): $entry"
  done

  dokku_log_verbose "denied users lose access on their next request; existing sessions are not honored"
  fn-ga-apply-list-change "$scope"
}

cmd-google-auth-deny "$@"
