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

if [[ $# -ne 2 || ! -r $1 || ! -r $2 ]]; then
  echo "Usage: $0 <env-file> <smtp-password-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

SMTP_ENCRYPTION=${SMTP_ENCRYPTION:-ssl}
for variable in SMTP_SERVER SMTP_PORT SMTP_USER SMTP_FROM; do
  [[ -n ${!variable:-} ]] || { echo "$variable must be set" >&2; exit 2; }
done

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 SMTP_SERVER="$SMTP_SERVER" \
  -e SMTP_PORT="$SMTP_PORT" \
  -e SMTP_ENCRYPTION="$SMTP_ENCRYPTION" \
  -e SMTP_USER="$SMTP_USER" \
  -e SMTP_FROM="$SMTP_FROM" \
  gerrit sh -eu -c '
password=$(cat)
if [ -z "$password" ]; then
  echo "SMTP password must not be empty" >&2
  exit 2
fi

config=/var/gerrit/etc/gerrit.config
secure_config=/var/gerrit/etc/secure.config
git config -f "$config" --replace-all sendemail.enable true
git config -f "$config" --replace-all sendemail.smtpServer "$SMTP_SERVER"
git config -f "$config" --replace-all sendemail.smtpServerPort "$SMTP_PORT"
git config -f "$config" --replace-all sendemail.smtpEncryption "$SMTP_ENCRYPTION"
git config -f "$config" --replace-all sendemail.sslVerify true
git config -f "$config" --replace-all sendemail.smtpUser "$SMTP_USER"
git config -f "$config" --replace-all sendemail.from "$SMTP_FROM"

umask 077
git config -f "$secure_config" --replace-all sendemail.smtpPass "$password"
chmod 600 "$secure_config"
' < "$2"

"${compose[@]}" restart gerrit
