#!/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
	fi
}

add_script_func () {
	echo "⚙️ Add Data Initialisation Script to Netbox"
	./manage.py nbshell -c 'ManagedFile.objects.get_or_create(data_path="universal_init_data.py",file_root="scripts",file_path="universal_init_data.py")' 2>&1 || true
}

init_script_func () {
	echo "⚙️ Run Data Initialision"
	for filename in /opt/netbox/netbox/scripts/data/*.json; do
	echo "⚙️ Executing $filename"
		./manage.py runscript universal_init_data.InitializeJsonDataScript --data '{"file_path":"'$filename'"}' --commit >/dev/null 2>&1 || true
	done
}

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 && \
	# Add script to netbox
	add_script_func && \

	# run init data script
	init_script_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."
	# Add script to netbox
	add_script_func && \

	# run init data script
	init_script_func && \
	## Launch regular netbox entrypoint
	/opt/netbox/docker-entrypoint.sh /opt/netbox/launch-netbox.sh
fi