#!/usr/bin/env bash
set -Eeuo pipefail

if [[ $# -ne 1 || ! -r $1 ]]; then
  echo "Usage: $0 <env-file>" >&2
  exit 2
fi

config_file=$(cd -- "$(dirname -- "$1")" && pwd)/$(basename -- "$1")
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
set -a
# shellcheck source=/dev/null
source "$config_file"
set +a

: "${GERRIT_HOST:?set GERRIT_HOST in the env file}"
: "${GERRIT_SSH_PORT:?set GERRIT_SSH_PORT in the env file}"

compose=(docker compose --env-file "$config_file" -f "$script_dir/compose.yaml")
# Expanded by the shell inside the container.
# shellcheck disable=SC2016
"${compose[@]}" exec -T \
  -e GERRIT_HOST="$GERRIT_HOST" \
  -e GERRIT_SSH_PORT="$GERRIT_SSH_PORT" \
  gerrit sh -eu -c '
config=/var/gerrit/etc/gerrit.config
git config -f "$config" --replace-all sshd.advertisedAddress "${GERRIT_HOST}:${GERRIT_SSH_PORT}"
git config -f "$config" --replace-all plugin.plugin-manager.preload false
git config -f "$config" --replace-all plugin.delete-project.deleteTrashFoldersMaxAllowedTime "10 minutes"
'

"${compose[@]}" restart gerrit
