#!/usr/bin/env bash
# Runs (as root) on `dokku plugin:install` and `dokku plugin:update`.
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x

PLUGIN_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DOKKU_LIB_ROOT=${DOKKU_LIB_ROOT:-/var/lib/dokku}
DATA_ROOT="$DOKKU_LIB_ROOT/data/google-auth"

mkdir -p "$DATA_ROOT/global" "$DATA_ROOT/apps"

if command -v docker >/dev/null 2>&1; then
  echo "-----> Building dokku-google-auth service image (first build can take a few minutes)"
  docker image build -t dokku-google-auth:latest "$PLUGIN_DIR"
  # Pick up the new image if the service is already running. This goes through
  # fn-ga-service-start rather than its own `docker run` so an upgrade always
  # rewrites service.env first: recreating the container from the file an older
  # version left behind gives it stale settings — most damagingly a missing
  # GOOGLE_AUTH_APP_CONFIG_DIR, which makes the service ignore every per-app
  # access list and fall back to the global one.
  if [[ "$(docker container inspect -f '{{.State.Running}}' dokku-google-auth 2>/dev/null)" == "true" ]]; then
    echo "-----> Restarting google-auth service with the new image"
    # shellcheck disable=SC1091
    source "$PLUGIN_DIR/functions"
    if fn-ga-configured; then
      fn-ga-service-start
    else
      echo " !     google-auth is not fully configured; the running service keeps the old image" 1>&2
      echo " !     run 'dokku google-auth:configure' then 'dokku google-auth:restart'" 1>&2
    fi
  fi
else
  echo " !     docker not found; the google-auth service image was not built" 1>&2
fi

# Ownership and modes last: the steps above can rewrite service.env as root,
# and the dokku user has to be able to rewrite it from then on.
chown -R dokku:dokku "$DATA_ROOT" 2>/dev/null || true
chmod 700 "$DATA_ROOT"
# apps/ is bind-mounted into the service container, which runs as an
# unprivileged uid and must be able to traverse it to read per-app access
# lists. The 0700 on DATA_ROOT still keeps other host users out.
chmod 711 "$DATA_ROOT/apps"
