#!/bin/bash
source /root/envsetup/global-conf.sh

if ( apt-cache madison campus-manager | grep "campus-manager | " ); then
	# install cm
	if ( dpkg -s campus-manager >/dev/null 2>&1 ); then
		DEBIAN_FRONTEND=noninteractive apt-get install -y --reinstall campus-manager
	else
		DEBIAN_FRONTEND=noninteractive apt-get install -y campus-manager
	fi
	# configure nginx
	sed -i "s@server_name skyreach;@server_name ${CM_SERVER_NAME};@" /etc/nginx/sites-available/skyreach.conf
	service nginx restart
	# set sender address
	sender="${EMAIL_SENDER}"
	if [[ "${sender}" == "" || "${sender}" == "noreply@ubicast.eu" ]]; then
		if [[ "${CM_SERVER_NAME}" =~ .*\..* ]]; then
			sender="noreply@${CM_SERVER_NAME}"
		fi
	fi
	if [[ "${sender}" != "" && "${sender}" != "noreply@ubicast.eu" ]]; then
		echo "Using ${sender} as sender address for CM."
		if grep "DEFAULT_FROM_EMAIL" /home/skyreach/htdocs/skyreach_site/settings_override.py >/dev/null; then
			sed -i "s?[# ]*DEFAULT_FROM_EMAIL.*?DEFAULT_FROM_EMAIL = '${sender}'?" /home/skyreach/htdocs/skyreach_site/settings_override.py
		else
			echo "DEFAULT_FROM_EMAIL = '${sender}'" >> /home/skyreach/htdocs/skyreach_site/settings_override.py
		fi
	fi
else
	echo "${YELLOW}The campus-manager package is not available in APT repositories, install skipped.${NC}"
fi
