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

cmd-google-auth-unallow() {
  declare desc="remove a domain or address from the allow list"
  local cmd="google-auth:unallow"
  [[ "$1" == "$cmd" ]] && shift 1

  [[ $# -gt 0 ]] || dokku_log_fail "usage: dokku google-auth:unallow <domain|address...> (see: dokku google-auth:allow)"

  # Lowercase, drop any leading "@", and de-duplicate so the lockout check
  # below counts each entry once.
  local entries=()
  mapfile -t entries < <(printf '%s\n' "$@" | tr '[:upper:]' '[:lower:]' | sed 's/^@//' | awk '!seen[$0]++')

  # Refuse before touching anything if this would leave the allow list empty,
  # which locks everyone out of every enabled app.
  local entry total present=0
  total=$(($(fn-ga-global-list-count allowed-domains) + $(fn-ga-global-list-count allowed-emails)))
  for entry in "${entries[@]}"; do
    fn-ga-global-list-contains allowed-domains "$entry" && present=$((present + 1))
    fn-ga-global-list-contains allowed-emails "$entry" && present=$((present + 1))
  done
  if [[ $((total - present)) -le 0 ]]; then
    dokku_log_fail "that would empty the allow list and lock everyone out; add the replacement first with: dokku google-auth:allow <domain|address>"
  fi

  local removed
  for entry in "${entries[@]}"; do
    removed=false
    if fn-ga-global-list-contains allowed-domains "$entry"; then
      fn-ga-global-list-remove allowed-domains "$entry"
      dokku_log_info1 "removed allowed domain: $entry"
      removed=true
    fi
    if fn-ga-global-list-contains allowed-emails "$entry"; then
      fn-ga-global-list-remove allowed-emails "$entry"
      dokku_log_info1 "removed: $entry"
      removed=true
    fi
    [[ "$removed" == "true" ]] || dokku_log_warn "$entry was not on the allow list"
  done

  dokku_log_verbose "removed users lose access on their next request; existing sessions are not honored"
  fn-ga-reload-service-config
}

cmd-google-auth-unallow "$@"
