#!/bin/bash
# postinst script for openems-edge
#
# Copyright (C) 2014-2023 Stefan Feilmeier <stefan.feilmeier@fenecon.de>
#
# 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 3 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 -o errexit

function start_service {
	/bin/systemctl daemon-reload

	# Check if service is enabled and running
	/bin/systemctl --quiet is-enabled $1 > /dev/null && {
		# Enabled - restart
		echo "Starting $1"
		/bin/systemctl start --no-block $1.service
	} || {
		# Not enabled - enable and start
		echo "Enabling and starting $1"
		/bin/systemctl stop $1.service
		/bin/systemctl enable $1.service
		/bin/systemctl start --no-block $1.service
	}
}

case "$1" in
	configure)
		# Always restart openems
		/bin/systemctl stop openems
		
		# Enable and start services
		start_service openems
		start_service nginx
		;;
		
	abort-upgrade|abort-remove|abort-deconfigure)
		;;

	*)
		echo "postinst called with unknown argument \`$1'" >&2
		;;
esac

