#!/bin/bash

set -e

cat <<EOF

                     A
 _     _   _     _       _                 _
| |__ | |_| |__ | | __ _| |__  ___   _ __ | |
| '_ \| __| '_ \| |/ _\` | '_ \/ __| | '_ \| |
| |_) | |_| | | | | (_| | |_) \__ \_| |_) | |
|_.__/ \__|_| |_|_|\__,_|_.__/|___(_) .__/|_|
                                    |_|
                production

HotPocket v25.10.1 [${HOTPOCKET_BACKEND_IMAGE_ID}] (https://hotpocket.app/)
Copyright 2025-present by BTHLabs. All rights reserved. (https://bthlabs.pl/)
Licensed under Apache-2.0
EOF

export PYTHONPATH="/srv/app:$PYTHONPATH"

if [ -n "${HOTPOCKET_BACKEND_RUN_MIGRATIONS}" ];then
    echo; echo "--- Running migrations..."
    ${VIRTUAL_ENV}/bin/python /srv/app/manage.py migrate
fi

if [[ -n "${HOTPOCKET_BACKEND_INITIAL_ACCOUNT_USERNAME}" && -n "${HOTPOCKET_BACKEND_INITIAL_ACCOUNT_PASSWORD}" ]]; then
    echo; echo "--- Creating initial Account..."
    ${VIRTUAL_ENV}/bin/python /srv/app/manage.py create_initial_account "${HOTPOCKET_BACKEND_INITIAL_ACCOUNT_USERNAME}" "${HOTPOCKET_BACKEND_INITIAL_ACCOUNT_PASSWORD}"
fi

if [ "${HOTPOCKET_BACKEND_ENV}" = "aio" ];then
    mkdir -p "${HOTPOCKET_BACKEND_UPLOADS_PATH:-/srv/run/uploads}"
fi

echo; echo "--- Running entrypoint.d parts..."
find "/srv/etc/entrypoint.d/" -follow -type f -print | sort -V | while read -r ENTRYPOINT_PART; do
    case "$ENTRYPOINT_PART" in
        *.sh)
            echo "$0: Executing ${ENTRYPOINT_PART}...";
            "$ENTRYPOINT_PART"
            ;;

        *)
            echo "$0: Ignoring ${ENTRYPOINT_PART}..."
            ;;
    esac
done

echo; echo "--- Setup done, booting the app..."; echo

exec /usr/bin/dumb-init "$@"
