#!/bin/sh

NET_SWITCH_DIR="/boot/home/net_switch"

if ! unzip -v bone.zip > /dev/null; then
	echo "The BONE archive is damaged! Aborting install."
	exit 1
fi

mkdir $NET_SWITCH_DIR
cp scripts/setbone $NET_SWITCH_DIR/
cp scripts/setnetserver $NET_SWITCH_DIR/
chmod +x $NET_SWITCH_DIR/setbone $NET_SWITCH_DIR/setnetserver 

# backup the netserver specific files if we have not done so yet
if [ ! -d $NET_SWITCH_DIR/netserver_d ]; then
	mkdir $NET_SWITCH_DIR/netserver_d
	mkdir $NET_SWITCH_DIR/netserver_d/bin
	
	cp /system/add-ons/kernel/drivers/bin/tulip $NET_SWITCH_DIR/tulip.old
	cp /system/boot/Netscript $NET_SWITCH_DIR/netserver_d
	cp /system/lib/libnet.so $NET_SWITCH_DIR/netserver_d
	cp /bin/ping $NET_SWITCH_DIR/netserver_d/bin/ping
	cp /bin/ftp $NET_SWITCH_DIR/netserver_d/bin/ftp
	cp /bin/telnet $NET_SWITCH_DIR/netserver_d/bin/telnet
	cp /bin/ftpd $NET_SWITCH_DIR/netserver_d/bin/ftpd
	cp /bin/telnetd $NET_SWITCH_DIR/netserver_d/bin/telnetd
fi

mv -f /system/add-ons/kernel/drivers/bin/ether $NET_SWITCH_DIR/ether.old
mv -f /system/add-ons/kernel/drivers/bin/etherpci $NET_SWITCH_DIR/etherpci.old

./update_conf_files

/bin/unzip -o -d /boot bone.zip

# backup the BONE specific files so we can quickly switch between the netserver and BONE
mkdir $NET_SWITCH_DIR/bone_d
mkdir $NET_SWITCH_DIR/bone_d/bin

cp /system/boot/Netscript $NET_SWITCH_DIR/bone_d
cp /system/lib/libnet.so $NET_SWITCH_DIR/bone_d
cp /system/lib/libnetapi.so $NET_SWITCH_DIR/bone_d
cp /bin/ping $NET_SWITCH_DIR/bone_d/bin/ping
cp /bin/ftp $NET_SWITCH_DIR/bone_d/bin/ftp
cp /bin/telnet $NET_SWITCH_DIR/bone_d/bin/telnet
cp /bin/ftpd $NET_SWITCH_DIR/bone_d/bin/ftpd
cp /bin/telnetd $NET_SWITCH_DIR/bone_d/bin/telnetd

# mark BONE as the current setting
touch $NET_SWITCH_DIR/bone_d/set

#setup services
mkdir /etc/net.d
ln -s /bin/inetd /etc/net.d/inetd
rm -f /etc/net.d/mail_daemon
printf '#!/bin/sh\r\n/system/servers/mail_daemon -E &\r\n' > /etc/net.d/net
chmod +x /etc/net.d/net
ln -s /system/servers/mail_daemon /etc/net.d/mail_daemon

# Setup development environment for bone
if ! grep C_INCLUDE_PATH /boot/home/.profile > /dev/null; then
	printf "export C_INCLUDE_PATH=/boot/develop/headers/be/bone/\nexport CPLUS_INCLUDE_PATH=/boot/develop/headers/be/bone/\n" >> /boot/home/.profile
fi

rm -f /boot/develop/headers/be/net/socket.h
rm -f /boot/develop/headers/posix/sys/socket.h
rm -f /boot/develop/headers/be/posix/sys/socket.h
rm -f /boot/develop/headers/be/net/netdb.h
rm -f /boot/develop/headers/be/net/netinet/in.h

echo "BONE installed.  Please hit enter to reboot..."
read BOGUS
/bin/shutdown -r
