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

cmd-google-auth-configure() {
  declare desc="configure the shared Google OAuth service"
  local cmd="google-auth:configure"
  [[ "$1" == "$cmd" ]] && shift 1

  local domains=() emails=() denied=()
  local domains_given=false emails_given=false denied_given=false
  local old_port
  old_port="$(fn-ga-global-get port "$GOOGLE_AUTH_DEFAULT_PORT")"

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --client-id)
        [[ -n "${2:-}" ]] || dokku_log_fail "--client-id requires a value"
        fn-ga-global-set client-id "$2"
        shift 2
        ;;
      --client-secret)
        [[ -n "${2:-}" ]] || dokku_log_fail "--client-secret requires a value"
        fn-ga-global-set client-secret "$2"
        shift 2
        ;;
      --auth-host)
        [[ -n "${2:-}" ]] || dokku_log_fail "--auth-host requires a value"
        local host="${2#https://}"
        host="${host#http://}"
        host="${host%/}"
        fn-ga-global-set auth-host "${host,,}"
        shift 2
        ;;
      --allow-domain)
        [[ -n "${2:-}" ]] || dokku_log_fail "--allow-domain requires a value"
        domains_given=true
        domains+=("${2,,}")
        shift 2
        ;;
      --allow-email)
        [[ -n "${2:-}" ]] || dokku_log_fail "--allow-email requires a value"
        emails_given=true
        emails+=("${2,,}")
        shift 2
        ;;
      --deny-email)
        [[ -n "${2:-}" ]] || dokku_log_fail "--deny-email requires a value"
        [[ "$2" == *@* ]] || dokku_log_fail "--deny-email takes a full address (got '$2'); denying a whole domain means removing its --allow-domain"
        denied_given=true
        denied+=("${2,,}")
        shift 2
        ;;
      --clear-deny-emails)
        denied_given=true
        shift 1
        ;;
      --session-ttl)
        [[ "${2:-}" =~ ^[0-9]+(h|m|s)$ ]] || dokku_log_fail "--session-ttl must look like 24h, 30m, or 3600s"
        fn-ga-global-set session-ttl "$2"
        shift 2
        ;;
      --cookie-name)
        [[ -n "${2:-}" ]] || dokku_log_fail "--cookie-name requires a value"
        fn-ga-global-set cookie-name "$2"
        shift 2
        ;;
      --port)
        [[ "${2:-}" =~ ^[0-9]+$ ]] || dokku_log_fail "--port must be a number"
        fn-ga-global-set port "$2"
        shift 2
        ;;
      --insecure-allow-http)
        # For local/dev testing only; Google requires https redirect URIs.
        fn-ga-global-set allow-insecure true
        shift 1
        ;;
      --regenerate-cookie-secret)
        fn-ga-global-set cookie-secret "$(head -c32 /dev/urandom | od -An -tx1 | tr -d ' \n')"
        dokku_log_info1 "cookie secret regenerated; all existing sessions are now invalid"
        shift 1
        ;;
      *)
        dokku_log_fail "unknown flag: $1 (see: dokku google-auth:help)"
        ;;
    esac
  done

  # Replace the allow/deny lists only when new values were passed.
  [[ "$domains_given" == "true" ]] && fn-ga-global-set-list allowed-domains "${domains[@]}"
  [[ "$emails_given" == "true" ]] && fn-ga-global-set-list allowed-emails "${emails[@]}"
  [[ "$denied_given" == "true" ]] && fn-ga-global-set-list denied-emails "${denied[@]}"

  # Deny wins over allow; surface the contradiction instead of silently
  # ignoring the allow entry.
  local addr
  while IFS= read -r addr; do
    [[ -z "$addr" ]] && continue
    if fn-ga-global-get-list allowed-emails | grep -qxF "$addr"; then
      dokku_log_warn "$addr is in both the allow and deny lists; it will be denied"
    fi
  done < <(fn-ga-global-get-list denied-emails)

  # First run: generate the cookie secret automatically.
  if [[ -z "$(fn-ga-global-get cookie-secret)" ]]; then
    fn-ga-global-set cookie-secret "$(head -c32 /dev/urandom | od -An -tx1 | tr -d ' \n')"
  fi

  if ! fn-ga-configured; then
    dokku_log_warn "configuration incomplete — required: --client-id, --client-secret, --auth-host, and at least one --allow-domain or --allow-email"
    dokku_log_warn "settings so far are saved; run google-auth:configure again with the missing flags"
    return 0
  fi

  fn-ga-service-start

  local new_port
  new_port="$(fn-ga-global-get port "$GOOGLE_AUTH_DEFAULT_PORT")"
  if [[ "$new_port" != "$old_port" ]]; then
    dokku_log_info1 "service port changed; regenerating nginx config for enabled apps"
    fn-ga-apply-all
  fi

  local auth_host
  auth_host="$(fn-ga-global-get auth-host)"
  dokku_log_info2 "google-auth configured"
  dokku_log_verbose "Register this redirect URI in the Google Cloud Console for your OAuth client:"
  dokku_log_verbose ""
  dokku_log_verbose "    https://${auth_host}${GOOGLE_AUTH_ROUTE_PREFIX}/callback"
  dokku_log_verbose ""
  dokku_log_verbose "Then protect apps with: dokku google-auth:enable <app>"
  fn-ga-warn-if-auth-host-unrouted
}

cmd-google-auth-configure "$@"
