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

#   Copyright (c) 2012-2013, 2015, 2019, 2025  Luke T. Shumaker <lukeshu@parabola.nu>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

set -e
. /etc/conf.d/parabolaweb
. libremessages

clean() {
	cd "$WEBDIR"
	msg "Purging old .pyc files..."
	find . -name '*.pyc' -delete
	if $RUNMAKE &>/dev/null; then
		msg "Purging old GNU Make generated files..."
		make clean
	fi
}

configure() {
	cd "$WEBDIR"
	msg "Checking configuration..."
	if [[ ! -f local_settings.py ]]; then
		msg2 "Configuration file missing, opening editor..."
		cp local_settings.py.example local_settings.tmp.$$.py
		if "$EDITOR" local_settings.tmp.$$.py; then
			mv local_settings.tmp.$$.py local_settings.py
		else
			rm local_settings.tmp.$$.py
			msg "Failed to configure, exiting"
			exit 1
		fi
		msg2 "Creating database..."
		./manage.py syncdb
	else
		msg2 "Current configuration checks out"
	fi
}

update-database() {
	cd "$WEBDIR"
	msg "Updating database..."
	msg2 "Running migrations..."
	./manage.py migrate
	msg2 "Loading fixtures..."
	./manage.py loaddata main/fixtures/*.json
	./manage.py loaddata devel/fixtures/*.json
	./manage.py loaddata mirrors/fixtures/*.json
	./manage.py loaddata releng/fixtures/*.json
	msg2 "Applying manual SQL..."
	engine=$(python -c 'from local_settings import DATABASES; print(DATABASES["default"]["ENGINE"].split(".")[-1])')
	for file in packages/sql/*."$engine".sql; do
		plain '%s' "$file"
		./manage.py dbshell <"$file"
	done
}

update-filesystem() {
	cd "$WEBDIR"
	msg "Updating filesystem..."
	if $RUNMAKE &>/dev/null; then
		msg2 "Re-creating GNU Make generated files..."
		make
	fi
	msg2 "Collecting static files..."
	./manage.py collectstatic --noinput --link
}

main() {
	if [[ -z "$EDITOR" ]]; then
		error 'Please set the $EDITOR variable'
		exit 1
	fi

	if [[ -d "$WEBDIR" ]]; then
		clean
	fi
	gitget checkout "$GITURL" "$WEBDIR"
	if [[ -d "${WEBDIR}/env" ]]; then
		python -m venv env
		. "${WEBDIR}/env/bin/activate"
		cd "$WEBDIR"
		pip install -r requirements_prod.txt
	fi
	configure
	update-database
	update-filesystem
	sudo systemctl stop uwsgi@parabolaweb.service
}

main "$@"
