#!/bin/bash
# reconfigure: no
# reconfigure-title: Listmonk
# reconfigure-description: Complete initial Listmonk setup.
set -e
. /etc/default/inithooks
[ ! -e "$INITHOOKS_CONF" ] || . "$INITHOOKS_CONF"

# The generated headless address is a placeholder, not an owner's address.
# Keep the app private until an interactive owner supplies its real address.
generated_hash_file="${INITHOOKS_CONF}.headless-generated.sha256"
if [[ -z "${_TURNKEY_INIT:-}" && "${AUTO_RUN:-}" == TRUE &&
      "${APP_DOMAIN:-}" == DEFAULT && -f "$generated_hash_file" &&
      -f "$INITHOOKS_CONF" ]]; then
    read -r generated_hash _ < "$generated_hash_file" || true
    if [[ "$generated_hash" =~ ^[0-9a-f]{64}$ &&
          "$(sha256sum < "$INITHOOKS_CONF")" == "$generated_hash  -" ]]; then
        echo 'Listmonk setup will continue at the first interactive login.'
        exit 0
    fi
fi

# Pass the password separately so dialog retains its controlling terminal.
"$INITHOOKS_PATH/bin/listmonk-setup" --pass-fd 3 \
    --domain "${APP_DOMAIN:-}" --email "${APP_EMAIL:-}" 3<<<"${APP_PASS:-}"
