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

cmd-google-auth-rebuild() {
  declare desc="rebuild the auth service image from the plugin source and restart"
  local cmd="google-auth:rebuild"
  [[ "$1" == "$cmd" ]] && shift 1

  # Starting the service already rebuilds when the Go source has moved, so this
  # exists for the case that check cannot see: the source is unchanged but the
  # build inputs are not — a patched base image, a half-written image, a build
  # that failed partway.
  local no_cache=false
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --no-cache) no_cache=true ;;
      *) dokku_log_fail "usage: dokku $cmd [--no-cache]" ;;
    esac
    shift
  done

  fn-ga-build-image "$no_cache"
  if fn-ga-service-running; then
    # The image is current now, so this recreates the container without
    # building a second time.
    fn-ga-service-start
  else
    dokku_log_verbose "auth service is not running; the new image is used when it starts"
  fi
}

cmd-google-auth-rebuild "$@"
