#!/bin/sh

fonfan_backup () {
	mv /www/cgi-bin/webif/ssh.sh /tmp/
	mv /www/cgi-bin/webif/fonfan.sh /tmp/
	mv /etc/fonfan_version /tmp/
	mv /etc/config/fonfan /tmp/
	mv /etc/init.d/*dropbear* /tmp/
	mv /www/cgi-bin/statistics.sh /tmp/
	mv /www/cgi-bin/status.sh /tmp/
	mv /www/cgi-bin/webif/backup.sh /tmp/
	mv /www/cgi-bin/webif/restore.sh /tmp/
}

fonfan_restore () {
	mv /tmp/ssh.sh /www/cgi-bin/webif/
	mv /tmp/fonfan.sh /www/cgi-bin/webif/
	mv /tmp/fonfan_version /etc/
	mv /tmp/fonfan /etc/config/
	mv /tmp/*dropbear* /etc/init.d/
	mv /tmp/statistics.sh  /www/cgi-bin/
	mv /tmp/status.sh /www/cgi-bin/
	mv /tmp/backup.sh /www/cgi-bin/webif/
	mv /tmp/restore.sh /www/cgi-bin/webif/
}


version="0.9.6a"

echo "Installing addons version $version"

echo "Freeing RAM..."
# Kill chilli if running to save RAM
killall N50chillispot
killall chilli

echo "Removing old files..."
fonfan_backup

echo "Downloading addons..."
if wget -O /tmp/addons.tar.gz http://addons.freewlan.info/installer/addons-"$version"_full.tar.gz
then
	echo "Extracting addons..."
	tar -xzf /tmp/addons.tar.gz -C /

	echo "Installing ipkg and rmdir fix..."
	rm -f /usr/bin/ipkg
	mv /tmp/ipkg.fixed /usr/bin/ipkg
	rm -f /bin/rmdir
	mv /tmp/rmdir.fixed /bin/rmdir

	echo "$version" > /etc/addon_version

	rm -f /tmp/addons.tar.gz

	echo "Finished installing addons version $version"

	echo "Searching for Updates..."
	/bin/autoupdate.sh manual

	echo "You shoud reboot now, type reboot"
	echo "If you need ssh and webif access from the LAN-/Internet-Port edit the file /etc/config/remote and set all values to 1"
else
	echo "Install faild, cant get addons.tar.gz, restoring files"
	fonfan_restore
	echo "Done"
fi
