#!/bin/bash

# Parse DATABASE_URL into PG* vars for PHP and psql
source bin/export_pg_vars.sh

# Set defaults for Caddy env vars
export CALENDARS_FRONTEND_ROOT="${CALENDARS_FRONTEND_ROOT:-/app/build/frontend-out}"
export CALENDARS_FRONTEND_BACKEND_SERVER="${CALENDARS_FRONTEND_BACKEND_SERVER:-localhost:8000}"
export DJANGO_ADMIN_URL="${DJANGO_ADMIN_URL:-admin}"

# Start PHP-FPM for SabreDAV (CalDAV server)
.php/usr/sbin/php-fpm8.3 \
  -n -c /app/.php/php.ini \
  --fpm-config /app/sabredav/php-fpm.conf \
  --nodaemonize &

# Start the Django backend
gunicorn -b :8000 calendars.wsgi:application --log-file - &

# Start the Caddy server
bin/caddy run --config Caddyfile --adapter caddyfile &

# if the current shell is killed, also terminate all its children
trap "pkill -SIGTERM -P $$" SIGTERM

# wait for a single child to finish,
wait -n
# then kill all the other tasks
pkill -P $$
