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

cmd-google-auth-allow() {
  declare desc="allow a domain or address to sign in, globally or for one app"
  local cmd="google-auth:allow"
  [[ "$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 allow list ($(fn-ga-scope-label "$scope"))"
    local listed found=false
    while IFS= read -r listed; do
      [[ -z "$listed" ]] && continue
      dokku_log_verbose "$listed (domain)"
      found=true
    done < <(fn-ga-list-get "$scope" allowed-domains)
    while IFS= read -r listed; do
      [[ -z "$listed" ]] && continue
      dokku_log_verbose "$listed"
      found=true
    done < <(fn-ga-list-get "$scope" allowed-emails)
    if [[ "$found" == "false" ]]; then
      if [[ "$scope" == "global" ]]; then
        dokku_log_verbose "(empty — nobody can sign in)"
      else
        dokku_log_verbose "(none — $scope uses the global allow list)"
      fi
    fi
    return 0
  fi

  local entry inherited=false
  [[ "$scope" != "global" && "$(fn-ga-list-count "$scope" allowed-domains)" -eq 0 &&
    "$(fn-ga-list-count "$scope" allowed-emails)" -eq 0 ]] && inherited=true

  for entry in "$@"; do
    fn-ga-validate-list-entry "$entry" ||
      dokku_log_fail "invalid entry '$entry' — use a domain (signal.org) or a full address (guest@partner.com), with no spaces or commas"
    entry="${entry,,}"
    if [[ "$(fn-ga-allow-entry-kind "$entry")" == "domain" ]]; then
      entry="${entry#@}"
      [[ "$entry" == *.* ]] || dokku_log_fail "'$entry' does not look like a domain"
      fn-ga-list-add "$scope" allowed-domains "$entry"
      dokku_log_info1 "allowed domain $(fn-ga-scope-label "$scope"): $entry (any verified account at $entry)"
    else
      fn-ga-list-add "$scope" allowed-emails "$entry"
      dokku_log_info1 "allowed $(fn-ga-scope-label "$scope"): $entry"
      if fn-ga-list-contains "$scope" denied-emails "$entry" ||
        fn-ga-list-contains global denied-emails "$entry"; then
        dokku_log_warn "$entry is on a deny list, which wins — run: dokku google-auth:undeny $(fn-ga-scope-arg "$scope") $entry"
      fi
    fi
  done

  # The first entry an app gets takes it off the global list entirely, which is
  # easy to do by accident.
  if [[ "$inherited" == "true" ]]; then
    dokku_log_warn "$scope no longer uses the global allow list — only the entries above can sign in to it"
  fi

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

cmd-google-auth-allow "$@"
