#!/bin/bash
# Configures a full development system for use as ramdisk.
# Set DEMO=1 to make it configured for the standard ramdisk demo that we ship

mode="$1"

case "$mode" in
on|enable|"")
	
	# Turn of some services started by /etc/rc
	for i in ssh hostapd inetd gpsd pcmcia ;
	do
		save_files ramdisk-configure /etc/rc*.d/*${i}
	        update-rc.d -f ${i} remove
	done

	# De-activate Xwindows and SSH and dbus and screen
	save_files ramdisk-configure /etc/rc?.d/S*xads.sh
	rm -f /etc/rc?.d/S*xads.sh
	save_files ramdisk-configure /etc/rc?.d/K*xads.sh
	rm -f /etc/rc?.d/K*xads.sh
	save_files ramdisk-configure /etc/rc?.d/S*ssh
	rm -f /etc/rc?.d/S*ssh
	save_files ramdisk-configure /etc/rc?.d/S*dbus-1
	rm -f /etc/rc?.d/S*dbus-1
	save_files ramdisk-configure /etc/rc?.d/S*screen-cleanup
	rm -f /etc/rc?.d/S*screen-cleanup

	# Generate unique host key for this image.
	save_files ramdisk-configure /etc/ssh/ssh_host_*_key*
	rm -f /etc/ssh/ssh_host_*_key*
	echo "Creating ssh keys, this will take some time."
	save_files ramdisk-configure /etc/ssh/ssh_host_rsa_key
	ssh-keygen -q -f /etc/ssh/ssh_host_rsa_key -N "" -t rsa
	save_files ramdisk-configure /etc/ssh/ssh_host_dsa_key
	ssh-keygen -q -f /etc/ssh/ssh_host_dsa_key -N "" -t dsa
	echo "Done creating ssh keys."

	if [ "$(dpkg --print-architecture)" = arm ]; then
		# Run cardmgr from inittab instead of /etc/rc
		# (recall pcmcia was turned off above)
		# (Armel doesn't use pcmcia-cs.)
		save_files ramdisk-configure /etc/inittab
		{
		echo '/^#cm:23/s/^#//'
		echo 'x'
		} | ex - /etc/inittab
	fi
	if [ "$DEMO" ]; then
		# Turn on microwindows
		cat << EOF >> /etc/inittab

# Microwindows / Nano-X
mw:3:once:/opt/nanox/nxstart.sh &
EOF
	fi

	if [ -f /usr/bin/w ]; then
		save_files ramdisk-configure /usr/bin/w
	        {
	        echo '#!/bin/sh'
	        echo 'uptime'
	        echo 'who'
	        } > /usr/bin/w
	        chmod a+x /usr/bin/w
	fi


	# Typical embedded system tricks
	save_files ramdisk-configure /var/tmp
	rm -rf /var/tmp
	ln -s /tmp /var/tmp
	# Disabled since restoring this is probably not a good idea and
	# /proc/mounts will work in most cases.
	#save_files ramdisk-configure /etc/mtab
	ln -sf /proc/mounts /etc/mtab

	# Use busybox utilities instead of the Debian ones.
	busybox-links enable

	echo "System is configured for use on a ramdisk."
	echo "Use 'adsrootbuilder -c ads-ramdisk.conf' to create a minimal ramdisk image."
	echo "Use 'ramdisk-configure off' to restore system to original configuration."
;;
off|disable)
	busybox-links disable
	restore_files ramdisk-configure
	echo "System restored from ramdisk configuration to original configuration."
;;
esac
