#!/bin/bash

#
# Put all localIPs for all HA systems here, as well as the floating IP
#
FLOATIP="192.168.230.12"
LOCALIPS="$FLOATIP 192.168.230.16 192.168.230.17"

SERVERDNS=***Enter server name ***
HTTPPORT=8880
FTPUSER=***Enter ftp user name***
FTPPASSWORD=***Enter ftp user password***

AASTRA_CFG=/tftpboot/aastra.cfg
TFTPDIR=/tftpboot
FTPDIR=/var/ftp

#
# Update the aastra.cfg to use an FTP configuration server
#
function update_aastra_cfg {
	/bin/grep -q "^ftp server" $AASTRA_CFG
	rc=$?
	[ $rc -eq 0 ] && return

	cat >>$AASTRA_CFG <<_EOF_

download protocol: FTP
ftp server: $SERVERDNS
ftp username: $FTPUSER
ftp password: $FTPPASSWORD
_EOF_
}

#
# Get the newest file in a directory
#
function getNewestFile {
	# using AWK:
	# f=`/bin/ls -lrt $1 | /bin/awk '{ f=$NF }; END{ print f }'`
	f=`/bin/ls -t1 $1 | /usr/bin/head -n1`
	#
	# Uncomment this if you want to find the newest file in a directory tree
	#
	#f=`/usr/bin/find $1 -not -type d -printf "%T+ %p\n" | /bin/sort -n | /usr/bin/tail -1 `

	echo "$1/$f"
}


newestTftpFile=$(getNewestFile $TFTPDIR)
newestFtpFile=$(getNewestFile $FTPDIR)


if [ $newestTftpFile -nt $newestFtpFile ]; then

	update_aastra_cfg

	for i in $TFTPDIR/*cfg; do
		for ip in $LOCALIPS; do
			/bin/sed -i "s|$ip|$SERVERDNS|" $i
		done
		/bin/sed -i "s|http://$SERVERDNS/|http://$SERVERDNS:$HTTPPORT/|" $i
		/bin/sed -i "s|http://$SERVERDNS:80|http://$SERVERDNS:$HTTPPORT|" $i
	done

	/usr/bin/rsync --delete -az $TFTPDIR/ $FTPDIR
	/bin/chmod 666 $TFTPDIR/*
	/bin/chown -R ftp.ftp $FTPDIR
	
	find $FTPDIR -type f -exec chmod 444 {} \; 
	#chmod -R 444 $FTPDIR/
	# Need to add executable bit back to directory
	#chmod -w $FTPDIR
	#chmod +x $FTPDIR
fi
