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

# Autogenerate missing values
if [ "${MS_ID}" = "" ]; then
	MS_ID=$(echo "$(hostname)_msuser")
	if ( cat "/root/envsetup/conf.sh" | grep "MS_ID" >/dev/null ); then
		sed -i "s@^MS_ID=.*@MS_ID='${MS_ID}'@" /root/envsetup/conf.sh
	else
		echo "MS_ID='${MS_ID}'" >> /root/envsetup/conf.sh
	fi
fi
if [ "${MS_API_KEY}" = "" ]; then
	MS_API_KEY=$(echo "s$(pwgen 4)-$(pwgen 5)-$(pwgen 5)-$(pwgen 5)-$(pwgen 5)")
	# respect API pattern
	MS_API_KEY=$(echo $MS_API_KEY | sed "s@[iloILO]@$((${RANDOM} / 10000))@g")
	if ( cat "/root/envsetup/conf.sh" | grep "MS_API_KEY" >/dev/null ); then
		sed -i "s@^MS_API_KEY=.*@MS_API_KEY='${MS_API_KEY}'@" /root/envsetup/conf.sh
	else
		echo "MS_API_KEY='${MS_API_KEY}'" >> /root/envsetup/conf.sh
	fi
fi
if [ "${MS_SECRET}" = "secret" ]; then
	MS_SECRET=$(echo "$(pwgen 40)")
	if ( cat "/root/envsetup/conf.sh" | grep "MS_SECRET" >/dev/null ); then
		sed -i "s@^MS_SECRET=.*@MS_SECRET='${MS_SECRET}'@" /root/envsetup/conf.sh
	else
		echo "MS_SECRET='${MS_SECRET}'" >> /root/envsetup/conf.sh
	fi
fi
# Worker IP for whitelist
if [ "${CELERITY_WORKER_IP}" = "" ]; then
	CELERITY_WORKER_IP=$(ip addr show | grep inet | grep -v 127 | grep -v ":" | awk -F " " '{print$2}' | awk -F "/" '{print$1}')
	if ( cat "/root/envsetup/conf.sh" | grep "CELERITY_WORKER_IP" >/dev/null ); then
		sed -i "s@^CELERITY_WORKER_IP=.*@CELERITY_WORKER_IP='${CELERITY_WORKER_IP}'@" /root/envsetup/conf.sh
	else
		echo "CELERITY_WORKER_IP='${CELERITY_WORKER_IP}'" >> /root/envsetup/conf.sh
	fi
fi
