#!/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 an allow list"
  local cmd="google-auth:unallow"
  [[ "$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 <domain|address...>"

  # 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]++')

  local entry total present=0
  total=$(($(fn-ga-list-count "$scope" allowed-domains) + $(fn-ga-list-count "$scope" allowed-emails)))
  for entry in "${entries[@]}"; do
    fn-ga-list-contains "$scope" allowed-domains "$entry" && present=$((present + 1))
    fn-ga-list-contains "$scope" allowed-emails "$entry" && present=$((present + 1))
  done

  # Emptying the global list locks everyone out of every enabled app, so refuse
  # before touching anything. Emptying an app's list is fine — it falls back to
  # the global one.
  if [[ "$scope" == "global" && $((total - present)) -le 0 ]]; then
    dokku_log_fail "that would empty the global allow list and lock everyone out; add the replacement first with: dokku google-auth:allow --global <domain|address>"
  fi

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

  if [[ "$scope" != "global" && $((total - present)) -le 0 ]]; then
    dokku_log_info1 "$scope has no allow entries left and now uses the global allow list"
  fi

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

cmd-google-auth-unallow "$@"
