#!/usr/bin/env bash
set -e

# Wait for Postgres to accept connections before migrating.
if [ -n "$POSTGRES_HOST" ]; then
  echo "Waiting for Postgres at $POSTGRES_HOST:$POSTGRES_PORT..."
  until python -c "import socket,os,sys; s=socket.socket(); s.settimeout(2); \
    sys.exit(0) if s.connect_ex((os.environ['POSTGRES_HOST'], int(os.environ.get('POSTGRES_PORT','5432'))))==0 else sys.exit(1)" 2>/dev/null; do
    sleep 1
  done
  echo "Postgres is up."
fi

# Only the web container should run migrations / collectstatic.
if [ "$RUN_MIGRATIONS" = "1" ]; then
  python manage.py migrate --noinput
  python manage.py seed_system_accounts
fi

exec "$@"
