#!/bin/bash

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

mkdir -p /dstar/tools /dstar/tmp /dstar/dv
cd /dstar/tools
rm -f dplus.last
if [ -f dplus ]; then
service dplus stop
mv dplus dplus.last
fi
curl -O http://www.opendstar.org/.admins/dplus
chmod 755 dplus
DPLUSVER=`./dplus -v`

if [ -f dplus-check.sh ]; then
rm -f dplus-check.sh.last
mv dplus-check.sh dplus-check.sh.last
fi
curl -O http://www.opendstar.org/.admins/dplus-check.sh
chmod 755 dplus-check.sh

if [ ! -f dplus-readdb ]; then
curl -O http://www.opendstar.org/.admins/dplus-readdb
chmod 755 dplus-readdb
fi

if [ ! -f dplus.conf ]; then
curl -O http://www.opendstar.org/.admins/dplus.conf
fi

cd /tmp

curl -O http://www.opendstar.org/.admins/dplus_init
cmp dplus_init /etc/init.d/dplus >/dev/null 2>&1
if [ ! -f /etc/init.d/dplus -o ! $? -eq 0 ]; then
	chmod 755 dplus_init
	mv dplus_init /etc/init.d/dplus
	chkconfig --add dplus
fi
rm -f dplus_init

if [ -d /opt/products/dstar/apache/securesite ]; then
if [ ! -d /opt/products/dstar/apache/securesite/dplus ]; then
curl -O http://www.opendstar.org/.admins/dplus-web.tgz
tar xPzf dplus-web.tgz
if [ ! -f /opt/products/dstar/apache/securesite/index.html ]; then
	ln -s /dstar/tmp/status.html /opt/products/dstar/apache/securesite/index.html
fi
fi
else
curl -O http://www.opendstar.org/.admins/dplus-web-ulf.tgz
cd /var/www/html
tar xPzf /tmp/dplus-web-ulf.tgz
if [ ! -f /var/www/html/index.html ]; then
	ln -s /dstar/tmp/status.html /var/www/html/index.html
fi
cd /tmp
fi

if [ ! -f /dstar/dv/remotesystemlinked.dvtool ]; then
cd /dstar/dv
curl -O http://www.opendstar.org/.admins/dplus-audio.tgz
tar xzvf dplus-audio.tgz
fi

DSTARGW=/opt/products/dstar/dstar_gw
DSIPSVD=$DSTARGW/dsipsvd/dsipsvd.conf
GW_CALL=`egrep -e '^ZR_CALLSIGN' $DSIPSVD | sed -e 's/ //g' | awk -F"=" '{print $2}' |sed -e 's/\r//'`

echo ""
echo "dplus $DPLUSVER installed"
echo ""

if [ ! -f /dstar/tmp/dvdonglemessage ]; then
echo "Welcome to the $GW_CALL D-Star repeater" >/dstar/tmp/dvdonglemessage
echo "file /dstar/tmp/dvdonglemessage was created, you may wish to edit your custom changes"
fi

service dplus start

