#!/bin/sh
# Starts one of three roles from the same image: web (default), queue or scheduler.
set -e
ROLE="${1:-${CONTAINER_ROLE:-web}}"
export CONTAINER_ROLE="$ROLE"
cd /var/www/html

# Wait for the database (up to 60 seconds).
i=0
until php -r 'try { new PDO("mysql:host=".getenv("DB_HOST").";port=".(getenv("DB_PORT")?:3306).";dbname=".getenv("DB_DATABASE"), getenv("DB_USERNAME"), getenv("DB_PASSWORD")); } catch (Exception $e) { exit(1); }' 2>/dev/null; do
    i=$((i+1)); [ "$i" -ge 30 ] && { echo "Database not reachable"; exit 1; }
    echo "Waiting for the database..."; sleep 2
done

if [ "$ROLE" = "web" ]; then
    # Volumes may be created as root; make sure PHP can write to them.
    chown -R www-data:www-data storage public/assets 2>/dev/null || true

    php artisan migrate --force --no-interaction
    php artisan optimize:clear >/dev/null
    php artisan config:cache && php artisan route:cache && php artisan view:cache
    php please stache:warm >/dev/null 2>&1 || true
    php please eloquent:sync-assets --container=assets --no-interaction >/dev/null 2>&1 || true

    # First start only: load the starting content when the site has no pages yet.
    if [ "${SEED_CONTENT_ON_FIRST_RUN:-true}" = "true" ] && \
       [ "$(php artisan tinker --execute='echo \Statamic\Facades\Entry::query()->where("collection","pages")->count();' 2>/dev/null | tail -1)" = "0" ]; then
        echo "Empty site: loading starting content"
        php artisan vnc:seed-content
    fi
    chown -R www-data:www-data storage 2>/dev/null || true
    exec supervisord -c /etc/supervisord.conf
fi

# Workers wait until the web container has run migrations.
sleep 15
php artisan config:cache >/dev/null

case "$ROLE" in
    queue)     exec su -s /bin/sh www-data -c "php artisan queue:work --sleep=3 --tries=3 --max-time=3600 --backoff=60" ;;
    scheduler) exec su -s /bin/sh www-data -c "php artisan schedule:work" ;;
    *)         exec "$@" ;;
esac
