#!/bin/bash
########################################################
# Select how to start Netbox Docker.
#  set env variable `ACTIVATE_WORKER_AND_HOUSEKEEPING` if needed to:
#  - 1
#  - 0 (legacy)
########################################################

migrate_func () {
	########################################################################################
	# Piece of code borrowed from netbox official `/opt/netbox/docker-entrypoint.sh` script.
	########################################################################################

	# Load correct Python3 env
	source /opt/netbox/venv/bin/activate

	# Check if update is needed
	if ! ./manage.py migrate --check >/dev/null 2>&1; then
	  echo "⚙️ Applying database migrations"
	  ./manage.py migrate --no-input
	  echo "⚙️ Running trace_paths"
	  ./manage.py trace_paths --no-input
	  echo "⚙️ Removing stale content types"
	  ./manage.py remove_stale_contenttypes --no-input
	  echo "⚙️ Removing expired user sessions"
	  ./manage.py clearsessions
	  echo "⚙️ Building search index (lazy)"
	  ./manage.py reindex --lazy
	  echo "⚙️ Initialising data"
	  ./manage.py runscript universal_init_data.InitializeJsonDataScript --data '{"file_path":"/opt/netbox/netbox/scripts/data/init_data.json"}' --commit
	fi
}

if [[ "${ACTIVATE_WORKER_AND_HOUSEKEEPING}" == 1 ]] ; then
	echo "var ACTIVATE_WORKER_AND_HOUSEKEEPING=1"
	echo "Netbox-worker and Netbox-housekeeping will not need extra containers to run."
	# run function.
	migrate_func && \
	# Start netbox with `netbox-worker` and `netbox-housekeeping` running on same container
	supervisord --configuration /etc/supervisor/conf.d/supervisord.conf
else
	echo "var ACTIVATE_WORKER_AND_HOUSEKEEPING=0"
	echo "Netbox-worker and Netbox-housekeeping might need separate containers to run."
	## Launch regular netbox entrypoint
	/opt/netbox/docker-entrypoint.sh /opt/netbox/launch-netbox.sh
fi