#! /bin/sh

### BEGIN INIT INFO
# Provides:          firstrun
# Required-Start:    $remote_fs
# Required-Stop:
# Should-Start:
# Default-Start:     S   
# Default-Stop:
# Short-Description: Script to run when first starting
# Description:       Something needs to be done when  is
#                    starting at first time.
#                      
#                    1. regenerate ssh host key
### END INIT INFO

N=/etc/init.d/firstrun
MEMTOTAL=$(awk 'BEGIN { printf "%.0f\n", '$(grep MemTotal /proc/meminfo | awk '{print $2}')'/1024/1024 }')

set -e

do_expand_rootfs(){
        device="/dev/mmcblk0"
        (echo d; echo n; echo p; echo 1; echo ; echo; echo w;) | fdisk $device 
return 0
}

case "$1" in
  start)
	    reboot=false
		#
		sed -e 's/#fbi/fbi/g' -i /etc/init.d/bootsplash
		#
		# if we have 1G ram reduce RAMLOG size 
		if [ "$MEMTOTAL" = 1 ]; then
			sed -e 's/TMPFS_RAMFS_SIZE=512m/TMPFS_RAMFS_SIZE=256m/g' -i /etc/default/ramlog
			# for cubieboard disable some services
			if [ -f "/boot/cubieboard2.bin" ]; then
				/sbin/insserv -r brcm40183-patch
				/sbin/insserv -r disable_led.sh
			fi
		fi
		#
		#
		#
		echo "First run. This process takes around 2 minutes to finish..." >> /dev/tty0
		echo "Creating ssh keys..." >> /dev/tty0

	        NEWMAC=00:01:43:`openssl rand -hex 3 | sed 's/\(..\)/\1:/g; s/.$//'`
                sed -e 's/ether/ether '$NEWMAC'/g' -i /etc/network/interfaces.default
                sed -e 's/ether/ether '$NEWMAC'/g' -i /etc/network/interfaces.hostapd
		# Cubietruck exception
		# if HDMI is attached during boot, set default screen output to HDMI
		if [ -n "$(dmesg | grep ParseEDID)" ] && [ -n "/boot/cubietruck.bin" ]; then
			bin2fex /boot/cubietruck.bin /tmp/tmp.fex
			sed -e 's/screen0_output_type.*/screen0_output_type     = 3/g' -i /tmp/tmp.fex
			fex2bin /tmp/tmp.fex /boot/cubietruck.bin
        fi
	        rm -f /etc/ssh/ssh_host*
                dpkg-reconfigure openssh-server >> /dev/tty0
		set +e
		#echo "Creating local sources list..." >> /dev/tty0
		#netselect-apt -s -n -o /etc/apt/sources.list >/dev/null 2>&1
		
		if [ "$(fping 8.8.8.8 | grep alive)" != "" ]; then
		echo "Downloading packages list..." >> /dev/tty0
		apt-get update >/dev/null 2>&1
	    #echo "Updating all packages..." >> /dev/tty0
	    #apt-get -y upgrade >/dev/null 2>&1
        #apt-get -y clean >/dev/null 2>&1
		fi
		
		echo "Expanding rootfs..." >> /dev/tty0
		if do_expand_rootfs;then
			echo "Expanding rootfs success, rebooting automatically." >> /dev/tty0
			/sbin/insserv resize2fs
	    	reboot=true
		else
			echo "Expanding rootfs has failed, see log files." >> /dev/tty0
		fi
		set -e
                update-rc.d bootsplash defaults
		/sbin/insserv -r firstrun
		if $reboot;then
			/sbin/reboot
		fi
        ;;
  *)
        echo "Usage: $N {start}" >&2
        exit 1
        ;;
esac

exit 0
