#!/bin/bash
echo "============================"
echo "Netsyms Business Accelerator"
echo "System Provisioning Tool"
echo "============================"
echo ""
echo ""

echo -n "Set client ID and key (only works on default configuration) (y/N)? "
read cloudyn
if [ "$cloudyn" == "y" ]; then
	echo -n "Enter cloud ID: "
	read cloudid
	echo -n "Enter cloud key: "
	read cloudkey
	sed -i "s/define(\"CLOUD_ID\", \"test\");/define(\"CLOUD_ID\", \"$cloudid\");/" /var/www/html/accelerator/settings.php
	sed -i "s/define(\"CLOUD_KEY\", \"test\");/define(\"CLOUD_KEY\", \"$cloudkey\");/" /var/www/html/accelerator/settings.php
	sed -i "s/proxy_pass https:\/\/test.netsyms.biz\//proxy_pass https:\/\/$cloudid.netsyms.biz\//" /etc/nginx/sites-enabled/default
	sed -i "s/test.netsyms.biz/$cloudid.netsyms.biz/" /etc/hosts
	echo "Sync settings saved."
fi

echo -n "Regenerate private keys (y/N)? "
read regenyn
if [ "$regenyn" == "y" ]; then
	echo "Regenerating SSH keys..."
	rm /etc/ssh/ssh_host_*
	/usr/sbin/dpkg-reconfigure openssh-server

	echo "Creating CJDNS key..."
	keystr=$(/opt/cjdns/makekeys | head -1)
	keyarr=($keystr)
	prikey=${keyarr[0]}
	pubkey=${keyarr[2]}
	ipv6=${keyarr[1]}
	pass=$(/opt/cjdns/mkpasswd)
	sed -i -E "s/\"privateKey\":\s+\"(.*)\"/\"privateKey\": \"$prikey\"/" /etc/cjdroute.conf
	sed -i -E "0,/\"publicKey\":\s+\"(.*)\"/s/\"publicKey\":\s+\"(.*)\"/\"publicKey\": \"$pubkey\"/" /etc/cjdroute.conf
	sed -i -E "0,/\"ipv6\":\s+\"(.*)\"/s/\"ipv6\":\s+\"(.*)\"/\"ipv6\": \"$ipv6\"/" /etc/cjdroute.conf
	sed -i -E "s/\{\"password\": \"(.*)\", \"user\": \"default-login\"\}/\{\"password\": \"$pass\", \"user\": \"default-login\"\}/" /etc/cjdroute.conf
fi

echo -n "Restart services (y/N)? "
read reloadyn
if [ "$reloadyn" == "y" ]; then
	echo "Restarting services..."
	echo "    CJDNS..."
	systemctl restart cjdns
	echo "    NGINX..."
	systemctl restart nginx
	echo "    SSH..."
	systemctl restart openssh-server
fi
echo ""
echo "Done."
