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

if ( apt-cache madison ubicast-skyreach-runtime | grep "ubicast-skyreach-runtime | " ); then
	echo "The ubicast-skyreach-runtime package is available in APT repositories."
else
	echo "${YELLOW}The ubicast-skyreach-runtime package is not available in APT repositories, install skipped.${NC}"
	exit 0
fi

# install cm
if ( dpkg -s ubicast-skyreach-runtime >/dev/null 2>&1 ); then
	DEBIAN_FRONTEND=noninteractive apt-get install -y --reinstall ubicast-skyreach ubicast-skyreach-runtime
else
	DEBIAN_FRONTEND=noninteractive apt-get install -y ubicast-skyreach-runtime
fi
# 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

# configure nginx
if [[ "${CM_SERVER_NAME}" != "" ]]; then
	/root/envsetup/set_app_domain.py mm $CM_SERVER_NAME
fi
nginx -t
service nginx restart
