#!/bin/bash -e
# generic preseeding of inithooks.conf if it doesn't exist

[ -n "$_TURNKEY_INIT" ] && exit 0

[ -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 (pseudo) random 12 char base64 password string
unset check response
while [ -z "$check" ]; do
    response="$(openssl rand -base64 9 2>/dev/null || true)"
    if [ ${#response} -ge 12 ]; then
        MASTERPASS=${response#\'}
        check=good
    else
        echo "opensll responded with something unexpected, so sleeping 1 sec, then retrying"
        sleep 1
    fi
done

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
EOF

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

