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

cmd-google-auth-enable() {
  declare desc="require Google sign-in for all requests to an app"
  local cmd="google-auth:enable"
  [[ "$1" == "$cmd" ]] && shift 1
  declare APP="$1"

  [[ -n "$APP" ]] || dokku_log_fail "usage: dokku google-auth:enable <app>"
  verify_app_name "$APP"
  fn-ga-configured || dokku_log_fail "google-auth is not configured yet; run: dokku google-auth:configure"

  if ! fn-ga-service-running; then
    dokku_log_info1 "auth service is not running; starting it"
    fn-ga-service-start
  fi

  fn-ga-app-set-enabled "$APP" true
  fn-ga-apply "$APP"

  dokku_log_info2 "Google auth enabled for $APP"
  dokku_log_verbose "Authenticated requests reach the app with these headers:"
  dokku_log_verbose "    X-Forwarded-Email / X-Auth-Request-Email  — signed-in Google email"
  dokku_log_verbose "    X-Forwarded-User  / X-Auth-Request-User   — stable Google account id"
  dokku_log_verbose "    X-Auth-Request-Name                       — display name"
  fn-ga-warn-if-auth-host-unrouted
}

cmd-google-auth-enable "$@"
