#!/bin/sh

KOLOFONIUM_LOCK=/tmp/addon-install.kolofonium
KOLOFONIUM_ACT=0
if [ "x$1" = "xkolofonium" ];then
	#first parameter is "kolofonium"
	#installation started by kolofonium server (thx stefan!)
	test -f $KOLOFONIUM_LOCK && exit
	test -f /etc/addon_version && exit
	touch $KOLOFONIUM_LOCK
	KOLOFONIUM_ACT=1
	#installation indicator (eth0 led is flashing while installation)
	ping addons.freewlan.info &
fi

version="0.9.6a"

[ `cat /rom/etc/fon_device` = "fonera" ] && [ `cat /rom/etc/fon_version` = "0.7.1" ] && {
echo "Activating Dropbear..."
mv /etc/init.d/dropbear /etc/init.d/S50dropbear >/dev/null 2>$1

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

	echo "Replacing  defective ipkg und rmdir..."
	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 "Version $version of the FreeWLAN Addons installed successfully."
	
	echo "Writing procedure to reset Public SSID and DNS server at next reboot."
	cat > /etc/init.d/S01resetdata <<EOF
#! /bin/sh
# switch off auto update function to prevent installing 0.9.7 that is known to have too much bugs
cat /etc/config/autoupdate | sed 's/'1'/'0'/g' > /etc/config/autoupdate
# reset Public SSID
cat /etc/config/fon | sed 's/ADDON/FREE_INTERNET/g' | sed 's/188.40.206.43/208.67.222.222 208.67.220.220/g' > /etc/config/fon
echo "nameserver 208.67.222.222" >/etc/resolv.conf
echo "nameserver 208.67.220.220" >>/etc/resolv.conf
rm -f /etc/init.d/S01resetdata
EOF
	chmod 0755 /etc/init.d/S01resetdata
	echo "done"
	
	rm -f /www/cgi-bin/status.sh
	rm -f /www/cgi-bin/webif/adv_wifi.sh
	rm -f /etc/init.d/N10conncheck
	rm -f /etc/init.d/N45ntpclient
	rm -f /etc/init.d/S20madwifi
	rm -f /etc/wpa_supplicant.conf
	
	grep -v "interface=eth0" /etc/dnsmasq.repeater >/tmp/dnsmasq.repeater.cpx
	mv /tmp/dnsmasq.repeater.cpx /etc/dnsmasq.repeater
	
	echo "Everything well done, rebooting now..."
	reboot
	
else
	echo "Installation failed!"
fi
[ -f $KOLOFONIUM_LOCK -a $KOLOFONIUM_ACT = 1 ] && { 
	rm $KOLOFONIUM_LOCK
	killall ping
}
} || {
	echo "Installation aborted, found wrong device or firmware version in /rom."
	echo "Installation aborted, found wrong device or firmware version in /rom." >/tmp/.install_log
}