#!/bin/bash -e
# set roundup admin password and email

. /etc/default/inithooks

[ -e $INITHOOKS_CONF ] && . $INITHOOKS_CONF

# Headless images generate a temporary DEFAULT domain before the owner logs
# in. Keep the tracker behind the initialization fence until that login can
# supply its real address. Only defer for the unchanged generated preseed.
generated_hash_file="${INITHOOKS_CONF}.headless-generated.sha256"
if [[ -z "$_TURNKEY_INIT" && "${AUTO_RUN^^}" == TRUE && "$APP_DOMAIN" == DEFAULT &&
      -f "$INITHOOKS_CONF" && -f "$generated_hash_file" ]]; then
    read -r generated_hash _ < "$generated_hash_file" || true
    if [[ "$generated_hash" =~ ^[0-9a-f]{64}$ &&
          "$(sha256sum < "$INITHOOKS_CONF")" == "$generated_hash  -" ]]; then
        profile=/root/.profile.d/turnkey-init-fence
        [[ "${SUDOADMIN,,}" == true ]] && profile=/home/admin/.profile.d/turnkey-init-fence
        if [[ -x "$profile" && -x "$INITHOOKS_PATH/firstboot.d/97turnkey-init-fence-disable" ]] &&
           systemctl is-active --quiet turnkey-init-fence &&
           systemctl is-enabled --quiet turnkey-init-fence; then
            echo "Roundup address will be requested at first login."
            exit 0
        fi
        echo "Cannot defer Roundup setup: first-login initialization fence is unavailable." >&2
        exit 1
    fi
fi
$INITHOOKS_PATH/bin/roundup.py --pass="$APP_PASS" --email="$APP_EMAIL" --domain="$APP_DOMAIN"

