#!/bin/bash

set -e

cat <<EOF

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

HotPocket v26.3.16 [${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"

echo; echo "--- Preparing the system..."

UPLOADS_PATH="${HOTPOCKET_BACKEND_UPLOADS_PATH:-/srv/uploads}"
if [ ! -d "${UPLOADS_PATH}" ];then
    mkdir -p "${UPLOADS_PATH}"
fi

sudo /srv/bin/fix-run-uploads-permissions.sh ${HOTPOCKET_BACKEND_APP_USER_UID} "${UPLOADS_PATH}"

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

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_CREATE_INITIAL_ACCOUNT}" ];then
    echo; echo "--- Creating initial Account..."
    ${VIRTUAL_ENV}/bin/python /srv/app/manage.py create_initial_account
fi

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

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