#!/bin/sh
# Picks the runtime each time the app starts, as Passenger does, so a deploy can change it without the panel
set -eu
cd "$BAKKBONE_APP_ROOT"
if [ -f passenger_wsgi.py ]; then
    py=python3
    [ -x .venv/bin/python ] && py=.venv/bin/python
    reload=
    [ "$BAKKBONE_APP_ENV" = development ] && reload=--reload
    exec "$py" -m gunicorn --bind "unix:$BAKKBONE_SOCKET" --umask 007 --workers "$BAKKBONE_WORKERS" --access-logfile - $reload passenger_wsgi:application
fi
if [ -f app.js ]; then
    exec node --require /opt/bakkbone/agent/share/bakkbone-listen.cjs app.js
fi
if [ -f config.ru ]; then
    export RACK_ENV="${RACK_ENV:-$BAKKBONE_APP_ENV}" RAILS_ENV="${RAILS_ENV:-$BAKKBONE_APP_ENV}"
    set -- --bind "unix://$BAKKBONE_SOCKET?umask=0007" --environment "$RACK_ENV" --threads 0:5 config.ru
    [ "$BAKKBONE_WORKERS" -gt 1 ] && set -- --workers "$BAKKBONE_WORKERS" "$@"
    # Ensure dependencies builds a bundle with Puma added, beside the app's own Gemfile rather than in it
    if [ -f .bakkbone/Gemfile ]; then
        export BUNDLE_GEMFILE="$BAKKBONE_APP_ROOT/.bakkbone/Gemfile" BUNDLE_PATH="$BAKKBONE_APP_ROOT/vendor/bundle"
        exec bundle exec puma "$@"
    fi
    if [ -f Gemfile ]; then
        echo "Run Ensure dependencies (bundle install) for $BAKKBONE_APP_ROOT first" >&2
        exit 1
    fi
    gems=/usr/local/lib/bakkbone/gems
    export GEM_PATH="$gems:$(ruby -e 'print Gem.default_path.join(":")')"
    [ -x "$gems/bin/puma" ] && exec "$gems/bin/puma" "$@"
    exec puma "$@"
fi
echo "There's no app.js (Node.js), passenger_wsgi.py (Python) or config.ru (Ruby) in $BAKKBONE_APP_ROOT" >&2
exit 1
