#!/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.pre22b ]; then
mv dplus.conf dplus.conf.pre22b
echo "/dstar/tools/dplus.conf has changed, you may need to edit your custom changes"
echo ""
echo "the original dplus.conf was saved as /dstar/tools/dplus.conf.pre22b"
echo ""
fi

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

cd /tmp

if [ ! -f /etc/init.d/dplus ]; then
curl -O http://dsyncg2.dstarusers.org/dplus_init
chmod 755 dplus_init
mv dplus_init /etc/init.d/dplus
chkconfig --add dplus
fi

if [ ! -d /opt/products/dstar/apache/securesite/dplus ]; then
curl -O http://www.opendstar.org/.admins/dplus-web.tgz
tar xPzvf 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

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
