#!/bin/bash -e
# reconfigure: yes
# reconfigure-title: Zen Cart
# reconfigure-description: Change the administrator password, email and store address.
# set zencart admin password, email and domain to serve

. /etc/default/inithooks

[ -e "$INITHOOKS_CONF" ] && . "$INITHOOKS_CONF"
[[ -n "${_TURNKEY_RECONFIGURE:-}" ]] && APP_EMAIL=''

# Keep the store fenced until a reachable address is supplied at first login.
if [[ -z "${_TURNKEY_INIT:-}" && "${AUTO_RUN^^}" == TRUE && "$APP_DOMAIN" == DEFAULT ]]; 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 "Zen Cart address will be requested at first login."
        exit 0
    fi
    echo "Cannot defer Zen Cart setup: first-login initialization fence is unavailable." >&2
    exit 1
fi
$INITHOOKS_PATH/bin/zencart.py --pass="$APP_PASS" --email="$APP_EMAIL" --domain="$APP_DOMAIN"

# The MySQL helpers restore MariaDB to the state they observed on entry.  The
# image build deliberately leaves it stopped, so make the appliance database
# available after firstboot has completed its credential changes.
service mariadb start

# Reload PHP's cached configuration as well as the web service after setup.
service apache2 restart
