#!/bin/bash -e
# reconfigure: no
# reconfigure-title: Headless Setup Defaults
# reconfigure-description: Prepare temporary credentials and defaults for unattended first boot.
# generic preseeding of inithooks.conf if it doesn't exist

# The preseed file is absent on fresh images; read its path independently.
source /etc/default/inithooks

# Only discard credentials this hook generated, and only while they are
# unchanged. Supplied or subsequently edited preseeds remain authoritative.
generated_hash_file="${INITHOOKS_CONF}.headless-generated.sha256"
if [[ -n "$_TURNKEY_INIT" ]]; then
    if [[ -f "$generated_hash_file" ]]; then
        read -r generated_hash _ < "$generated_hash_file" || true
        if [[ -f "$INITHOOKS_CONF" && "$generated_hash" =~ ^[0-9a-f]{64}$ ]] &&
            [[ "$(sha256sum < "$INITHOOKS_CONF")" == "$generated_hash  -" ]]; then
            rm -- "$INITHOOKS_CONF"
        fi
        # A changed, finalized or missing config also consumes stale provenance.
        rm -- "$generated_hash_file"
    fi
    exit 0
fi

[[ -e "$INITHOOKS_CONF" ]] && exit 0

# double check that openssl is installed, else fail loudly
if ! which openssl > /dev/null; then
    # possibly overkill, but send to both stdout & stderr
    echo "FATAL [$0]: openssl not installed" | tee /dev/stderr
    exit 1
fi

# Generate shell-safe fallback credentials that satisfy application policies.
# Rejection sampling keeps all 32 characters random while requiring each class.
unset check response
while [ -z "$check" ]; do
    response="$(openssl rand -base64 24 2>/dev/null || true)"
    if [[ "${#response}" -ne 32 || ! "$response" =~ ^[A-Za-z0-9+/]+$ ]]; then
        echo "openssl responded with something unexpected, so sleeping 1 sec, then retrying"
        sleep 1
    elif [[ "$response" =~ [A-Z] && "$response" =~ [a-z] &&
            "$response" =~ [0-9] && "$response" =~ [+/] ]]; then
        MASTERPASS=$response
        check=good
    fi
done

# Generated fallback credentials and their provenance are root-only.
umask 077
cat>"$INITHOOKS_CONF"<<EOF
export ROOT_PASS=$MASTERPASS
export DB_PASS=$MASTERPASS
export APP_PASS=$MASTERPASS
export APP_EMAIL=admin@example.com
export APP_DOMAIN=DEFAULT
export HUB_APIKEY=SKIP
export SEC_ALERTS=SKIP
export SEC_UPDATES=SKIP
export AUTO_RUN=TRUE
EOF
chmod 600 "$INITHOOKS_CONF"
sha256sum < "$INITHOOKS_CONF" > "$generated_hash_file"
chmod 600 "$generated_hash_file"

chmod +x /usr/lib/inithooks/firstboot.d/??turnkey-init-fence*
