#!/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"
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"

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.
  if [[ "$(docker container inspect -f '{{.State.Running}}' dokku-google-auth 2>/dev/null)" == "true" ]]; then
    echo "-----> Restarting google-auth service with the new image"
    port="$(head -n1 "$DATA_ROOT/global/port" 2>/dev/null || true)"
    port="${port:-2999}"
    docker container rm -f dokku-google-auth >/dev/null 2>&1 || true
    docker container run -d \
      --name dokku-google-auth \
      --restart=unless-stopped \
      -p "127.0.0.1:${port}:2999" \
      --env-file "$DATA_ROOT/service.env" \
      -v "$DATA_ROOT/apps:/data/apps:ro" \
      dokku-google-auth:latest >/dev/null
  fi
else
  echo " !     docker not found; the google-auth service image was not built" 1>&2
fi
