#!/bin/bash

PRODDIR=/opt/products/dstar

if [ $EUID != 0 ] ; then
        echo "installer must be run as root"
        exit
fi

if [ ! -d $PRODDIR ] ; then
	echo "$PRODDIR not found"
	exit
fi

DSTARGW=/opt/products/dstar/dstar_gw
DSIPSVD=$DSTARGW/dsipsvd/dsipsvd.conf

if [ ! -r $DSIPSVD ]; then
    echo "$DSIPSVD not found"
    exit
fi

GW_CALL=`egrep -e '^ZR_CALLSIGN' $DSIPSVD | sed -e 's/ //g' | awk -F"=" '{print $2}' |sed -e 's/\r//'`

cd /tmp

#G3 install
curl -O http://www.opendstar.org/.admins/.certs/dsgw-cert-install-G3.tgz

grep -q "AlmaLinux" /etc/redhat-release
if [ $? -eq 0 ];then
	if [ ! -f /etc/nginx/nginx.conf.ORIG ]; then
		curl -O http://www.opendstar.org/.admins/.certs/nginx.conf
		mv /etc/nginx/nginx.conf /etc/nginx.conf.ORIG
		mv nginx.conf /etc/nginx
	fi
	cd /etc/nginx
	tar xzf /tmp/dsgw-cert-install-G3.tgz
	systemctl restart nginx
else
	grep -q "CentOS release 6" /etc/redhat-release
	if [ $? -eq 0 ];then
		echo "Found redhat release 6"
		curl -O http://www.opendstar.org/.admins/.certs/ssl.conf-centos6-secure
		mv ssl.conf-centos6-secure ssl.conf
	else
		grep -q "CentOS Linux release 7" /etc/redhat-release
		if [ $? -eq 0 ];then
			echo "Found redhat release 7"
			curl -O http://www.opendstar.org/.admins/.certs/ssl.conf-centos7-secure
			mv ssl.conf-centos7-secure ssl.conf
		else
			echo "Unknown Linux release"
		fi
	fi
	if [ ! -f /etc/pki/tls/certs/dstargateway.org.crt ] ; then
	echo "backing up files"
	cp /etc/pki/tls/certs/localhost.crt /etc/pki/tls/certs/localhost.crt.pre-dstar
	cp /etc/pki/tls/private/localhost.key /etc/pki/tls/private/localhost.key.pre-dstar
	fi
	if [ ! -f /etc/httpd/conf.d/ssl.conf.ORIG ] ; then
		echo "backing up ssl config"
		cp /etc/httpd/conf.d/ssl.conf /etc/httpd/conf.d/ssl.conf.ORIG
	fi
	if [ -f ssl.conf ] ; then
		mv /etc/httpd/conf.d/ssl.conf /etc/httpd/conf.d/ssl.conf.LAST
		mv ssl.conf /etc/httpd/conf.d
	fi
	cd /etc/pki/tls
	tar xzf /tmp/dsgw-cert-install-G3.tgz
	cp /etc/pki/tls/certs/dstargateway.org.crt /etc/pki/tls/certs/localhost.crt
	cp /etc/pki/tls/private/dstargatewayorg.key /etc/pki/tls/private/localhost.key

	service httpd restart
fi

echo ""
echo "completed certificate installation for $GW_CALL"
echo "try http://$GW_CALL.dstargateway.org/"

exit 0
