#!/usr/bin/env bash

set -euo pipefail

start () {
  # Creates an uwsgi service with 4 processes (override by setting UWSGI_NUM_PROCESSES environment variable)
  # of the app.

  fmt='{"asctime": "%(ftime)", "rq_time_ms": %(tmsecs), "method": "%(method)", "uri": "%(uri)", "proto": "%(proto)", "status": %(status), "referer": "%(referer)", "user_agent": "%(uagent)", "remote_addr": "%(addr)", "http_host": "%(host)", "pid": %(pid), "worker_id": %(wid), "core": %(core), "async_switches": %(switches), "io_errors": %(ioerr), "rq_size": %(cl), "rs_time_ms": %(msecs), "rs_size": %(size), "rs_header_size": %(hsize), "rs_header_count": %(headers)}'

  exec uwsgi --http 0.0.0.0:80 \
       --http-keepalive=70 \
       --drop-after-init \
       --uid nobody \
       --gid nogroup \
       --log-date="%Y-%m-%d %H:%M:%S" \
       --logformat-strftime \
       --log-micros \
       --logformat "${fmt}" \
       --master \
       --processes ${UWSGI_NUM_PROCESSES:-4} \
       --lazy-apps \
       --need-app --module dispatch_trip.wsgi:app
}

if [[ -z "$@" ]]; then
  start
elif [[ "$@" == "migrate-and-run" ]]; then
  # NOTE: Do not use this option in production. It is not safe.
  # Local/dev only.
  python -c "import dispatch_trip.main as t; t.migrate()" upgrade head
  start
else
  exec $@
fi
