#!/bin/bash

set -e

# https://stackoverflow.com/questions/49778988/makemigrations-in-dev-machine-without-database-instance
CHECK_MIGRATIONS_SETTINGS=`mktemp`
trap "rm -f ${CHECK_MIGRATIONS_SETTINGS}" EXIT
cat <<EOF >${CHECK_MIGRATIONS_SETTINGS}
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.dummy',
    }
}
EOF
APPS=$(env DJANGO_SETTINGS_MODULE=authentic2.settings python -c 'from django.conf import settings; print(" ".join(p for p in (p.split(".")[-1] for p in settings.INSTALLED_APPS if not p.startswith("django.")) if p not in ["admin", "auth", "contenttypes"]))')
TEMPFILE=`mktemp`
trap "rm -f ${TEMPFILE} ${CHECK_MIGRATIONS_SETTINGS}" EXIT

AUTHENTIC2_SETTINGS_FILE=${CHECK_MIGRATIONS_SETTINGS}  ./authentic2-ctl makemigrations --dry-run --noinput ${APPS} >${TEMPFILE} 2>&1 || true

if ! grep 'No changes detected' -q ${TEMPFILE}; then
   echo '!!! Missing migration detected !!!'
   cat ${TEMPFILE}
   exit 1
else
   exit 0
fi
