#!/bin/bash

### BEGIN INIT INFO
# Provides:          firstrun
# Required-Start:    $all
# Required-Stop:
# Should-Start:      armhwinfo
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: PLEASE BE PATIENT AND DO NOT INTERRUPT THE FIRST REBOOT
# Description:       Something needs to be done when  is
#                    starting at first time.
#                    regenerate ssh host key
### END INIT INFO
#
# Create this file to speed up boot process
#

# Immediately exit if not called by init system
if [ "X$1" != "Xstart" ]; then
	exit 1
fi

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Log=/var/log/armhwinfo.log

# create helper script to set swap settings
cat > /tmp/create_swap.sh <<EOT
#!/bin/bash
# 
# create swap and adds it into fstab
#
# SSH Keys creation
rm -f /etc/ssh/ssh_host*
dpkg-reconfigure openssh-server >/dev/null 2>&1
echo -e "\n### [firstrun] Recreated SSH keys" >>${Log}
MEMTOTAL=$(( $(awk -F" " '/^MemTotal/ {print $2}' </proc/meminfo) / 1024 ))
FREESIZE=\$(df -hm / | awk '/\// {print \$(NF-2)}')
SWAPFILE=/var/swap
if [[ ! -f "$SWAPFILE" && "\$FREESIZE" -gt "132" ]]; then
fallocate -l 128M $SWAPFILE >/dev/null 2>&1
if [ $? -eq 1 ]; then dd if=/dev/zero of=$SWAPFILE bs=1M count=128 status=noxfer >/dev/null 2>&1; fi
chown root:root $SWAPFILE
chmod 0600 $SWAPFILE
mkswap $SWAPFILE >/dev/null 2>&1
swapon $SWAPFILE >/dev/null 2>&1
if ! grep -q swap /etc/fstab; then echo "$SWAPFILE none swap sw 0 0" >> /etc/fstab; fi
if ! grep -q swap /etc/sysctl.conf; then echo "vm.swappiness=0" >> /etc/sysctl.conf; fi
echo -e "\n### [firstrun] Created 128MB emergency swap as $SWAPFILE" >>${Log}
fi
# RAMLOG
if [[ "$(apt-cache policy ramlog | grep Installed)" != "" ]]; then
	service ramlog enable
	# if we have 1G ram reduce RAMLOG size 
	if [[ "\$MEMTOTAL" -lt "1100" ]]; then
		if [ -f "/etc/default/ramlog" ]; then					
			sed -e 's/TMPFS_RAMFS_SIZE=512m/TMPFS_RAMFS_SIZE=256m/g' -i /etc/default/ramlog
		fi
	elif [[ "\$MEMTOTAL" -lt "600" ]]; then
		if [ -f "/etc/default/ramlog" ]; then					
			sed -e 's/TMPFS_RAMFS_SIZE=512m/TMPFS_RAMFS_SIZE=192m/g' -i /etc/default/ramlog
		fi
	fi
fi
while [ -f /tmp/firstrun_running ]; do sleep 1; done
if [ -f "/var/run/reboot" ]; then reboot; fi
rm -f /tmp/create_swap.sh
EOT
chmod +x /tmp/create_swap.sh

collect_information() {
	# get some info about the board
	DISTRIBUTION=$(lsb_release -cs)
	HARDWARE=$(awk '/Hardware/ {print $3}' </proc/cpuinfo)
	# Mainline kernel fix
	[ "X${HARDWARE}" = "XAllwinner" ] && HARDWARE=$(awk '/Hardware/ {print $4}' </proc/cpuinfo)
	case ${DISTRIBUTION} in
		wheezy)
			root_device=$(mountpoint -d /)
			for file in /dev/* ; do
				CURRENT_DEVICE=$(printf "%d:%d" $(stat --printf="0x%t 0x%T" $file))
				if [ $CURRENT_DEVICE = $root_device ]; then
					root_partition=$file
					break;
				fi
			done
			rootfstype=$(blkid -s TYPE -o value $root_partition)
			;;
		*)
			ROOTFS=$(findmnt / | awk -F" " '/\/dev\// {print $2"\t"$3}')
			set ${ROOTFS}
			root_partition=$1
			rootfstype=$2
			;;
	esac
} # collect_information

display_alert() {
	if [ "${DISTRIBUTION}" == "wheezy" ]; then
		echo -e "[\e[0;32m ok \x1B[0m] ${1}" > /dev/tty1
	elif [ "${DISTRIBUTION}" == "jessie" ]; then
		echo -e "[\e[0;32m  OK  \x1B[0m] ${1}" > /dev/tty1
	else
		echo -e " * ${1}" > /dev/tty1
	fi
}

adjust_sunxi_settings() {
	# set some mac address for wifi	
	[[ "$(lsmod | grep 8189fs)" != "" ]] && \
		(MACADDR=$(printf '43:29:B1:%02X:%02X:%02X\n' $[RANDOM%256] $[RANDOM%256] $[RANDOM%256]) ; \
		echo "options 8189fs rtw_initmac=${MACADDR}" > /etc/modprobe.d/8189fs.conf ; \
		echo -e "\n### [firstrun] Use MAC address ${MACADDR} for Wi-Fi from now" >>${Log})

	# set some mac address for BT
	[[ "$(lsmod | grep bcmdhd)" != "" ]] && \
		(MACADDR=$(printf '43:29:B1:%02X:%02X:%02X\n' $[RANDOM%256] $[RANDOM%256] $[RANDOM%256]) ; \
		sed -i "s/^MAC_ADDR=.*/MAC_ADDR=${MACADDR}/" /etc/default/brcm40183 \
		echo -e "\n### [firstrun] Use MAC address ${MACADDR} for Bluetooth from now" >>${Log})
	
	# trigger red or blue LED as user feedback
	echo heartbeat >/sys/class/leds/*red*/trigger 2>/dev/null || echo heartbeat >/sys/class/leds/*blue*/trigger 2>/dev/null	
	[ -f /etc/wicd/wired-settings.conf ] && \
		read HOSTNAME </etc/hostname
		sed -i "s/^dhcphostname =.*/dhcphostname = ${HOSTNAME}/" /etc/wicd/wired-settings.conf && \
		sed -i "s/wpa_driver =.*/wpa_driver = none/" /etc/wicd/manager-settings.conf \
		echo -e "\n### [firstrun] Use ${HOSTNAME} for wicd settings" >>${Log}
} # adjust_sunxi_settings

do_expand_rootfs() {
	# get device node for boot media
	DEVICE="/dev/"$(lsblk -idn -o NAME | grep -w mmcblk0)
	if [ "${DEVICE}" = "/dev/" ]; then return ; fi
	QUOTED_DEVICE=$(echo "${DEVICE}" | sed 's:/:\\\/:g')
	
	# get count of partitions and their boundaries
	PARTITIONS=$(( $(grep -c ${DEVICE##*/}p /proc/partitions) ))
	PARTSTART=$(parted ${DEVICE} unit s print -sm | tail -1 | cut -d: -f2 | sed 's/s//') # start of first partition
	PARTEND=$(parted ${DEVICE} unit s print -sm | head -3 | tail -1 | cut -d: -f3 | sed 's/s//') # end of first partition
	STARTFROM=$(( ${PARTEND} + 1 ))
	[[ ${PARTITIONS} == 1 ]] && STARTFROM=${PARTSTART}
	
	# check whether a resizing rule is defined. We will take this value if it's not too low. In
	# this case the value will be ignored and resizing to the whole card size happens.
	if [ -f "/root/.rootfs_resize" ]; then
		read RESIZE_VALUE <"/root/.rootfs_resize"
		ResizeLog="Resize rule ${RESIZE_VALUE} defined for ${root_partition}"
		case ${RESIZE_VALUE} in
			*%)
				# percentage value, we try to use 16MiB to align partitions since this is
				# the erase block size of more recent SD cards (512 byte sectors, so we use 32
				# as divider and substract 1)
				PERCENTAGE=$(echo ${RESIZE_VALUE} | tr -c -d '[:digit:]')
				LASTSECTOR=$(( 32 * $(parted ${DEVICE} unit s print -sm | awk -F":" "/^${QUOTED_DEVICE}/ {printf (\"%0d\", ( \$2 * ${PERCENTAGE} / 3200))}") -1 ))
				if [ ${LASTSECTOR} -lt ${PARTEND} ]; then unset LASTSECTOR ; fi
				;;
			*s)
				# sector value, we use it directly
				LASTSECTOR=$(echo ${RESIZE_VALUE} | tr -c -d '[:digit:]')
				if [ ${LASTSECTOR} -lt ${PARTEND} ]; then unset LASTSECTOR ; fi
				;;
		esac
	else
		# Unattended mode. We run a q&d benchmark to be able to identify cards way too slow easily
		cd /root
		echo -e "\n### quick iozone test:\c" >>/var/log/armhwinfo.log
		iozone -e -I -a -s 1M -r 4k -i 0 -i 1 -i 2 | grep '^            1024' | sed 's/            1024      //' >>/var/log/armhwinfo.log

		# check device capacity. If 4GB or below do not use whole card but leave a 5% spare area
		# to help older cards with wear leveling and garbage collection. In case this reduced card
		# capacity is less than the actual image capacity this is a clear sign that someone wants
		# to use Armbian on a card of inappropriate size so he gets what he deserves (at least he
		# should know what he's doing)
		CAPACITY=$(parted ${DEVICE} unit s print -sm | awk -F":" "/^${QUOTED_DEVICE}/ {printf (\"%0d\", \$2 / ( 1024 / \$4 ))}")
		if [ ${CAPACITY} -lt 4000000 ]; then
			SPAREAREA=$(( ${CAPACITY} / 20000 ))
			LASTSECTOR=$(parted ${DEVICE} unit s print -sm | awk -F":" "/^${QUOTED_DEVICE}/ {print \$2 - (${SPAREAREA} * 1024 * ( 1024 / \$4 ))}")
			if [ ${LASTSECTOR} -lt ${PARTEND} ]; then
				unset LASTSECTOR
			else
				ResizeLog="4GB media so leaving 200MB spare area on ${root_partition}"
			fi
		elif [ ${CAPACITY} -lt 8000000 ]; then
			# Leave 2 percent unpartitioned
			LASTSECTOR=$(( 32 * $(parted ${DEVICE} unit s print -sm | awk -F":" "/^${QUOTED_DEVICE}/ {printf (\"%0d\", ( \$2 * 98 / 3200))}") -1 ))
			if [ ${LASTSECTOR} -lt ${PARTEND} ]; then
				unset LASTSECTOR
			else
				ResizeLog="8GB media so leaving 2 percent spare area on ${root_partition}"
			fi
		else
			# Leave 1 percent unpartitioned
            LASTSECTOR=$(( 32 * $(parted ${DEVICE} unit s print -sm | awk -F":" "/^${QUOTED_DEVICE}/ {printf (\"%0d\", ( \$2 * 99 / 3200))}") -1 ))
			if [ ${LASTSECTOR} -lt ${PARTEND} ]; then
				unset LASTSECTOR
			else
				ResizeLog="Leaving 1 percent spare area on ${root_partition}"
			fi
		fi
	fi

	# Start resizing
	echo -e "\n### [firstrun] ${ResizeLog}. Start resizing Partition now:\n" >>${Log}
	cat /proc/partitions >>${Log}
	echo -e "\nExecuting fdisk, fsck and partprobe:\n" >>${Log}
	if [ "X${DISTRIBUTION}" = "Xxenial" -a "X${PARTITIONS}" = "X1" ]; then
		((echo d; echo n; echo p; echo ; echo $STARTFROM; echo ${LASTSECTOR} ; echo w;) | fdisk ${DEVICE}) >>${Log} 2>&1 || true
	else
		((echo d; echo $PARTITIONS; echo n; echo p; echo ; echo $STARTFROM; echo ${LASTSECTOR} ; echo w;) | fdisk ${DEVICE}) >>${Log} 2>&1 || true
	fi
	echo -e "\nNew partition table:\n" >>${Log}
	s=0	
	fsck -f $root_partition >>${Log} ll 2>&1 || true
	partprobe ${DEVICE} >>${Log} ll 2>&1 || s=$?
	echo -e "\nNew partition table:\n" >>${Log}
	cat /proc/partitions >>${Log}
	echo -e "\nNow executing resize2fs to enlarge ${root_partition} to the maximum\n:" >>${Log}
	resize2fs $root_partition >>${Log} 2>&1 || true
	
	# check whether reboot is necessary for resize2fs to take effect
	FREESIZE=$(df -hm / | awk '/\// {print $(NF-2)}')
	if [[ "$DISTRIBUTION" == "wheezy" || "$s" != "0" || "$FREESIZE" -lt "152" ]]; then
		touch /var/run/reboot
		display_alert "Automatic reboot is needed. Please wait"
		update-rc.d resize2fs defaults >/dev/null 2>&1
		echo -e "\n### [firstrun] Automated reboot needed to let /etc/init.d/resize2fs do the job\n" >>${Log}
	fi
	return 0
} # do_expand_rootfs

check_prerequisits() {
	for needed_tool in fdisk parted partprobe resize2fs ; do
		which ${needed_tool} >/dev/null 2>&1 || exit 1
	done
} # check_prerequisits

main() {
	check_prerequisits
	collect_information

	if [[ "$rootfstype" == "ext4" && ! -f "/root/.no_rootfs_resize" ]]; then
		display_alert "Resizing root filesystem."
		do_expand_rootfs
	fi

	display_alert "Starting 128Mb emergency swap area creation."
	display_alert "Starting SSH keys recreation."

	touch /tmp/firstrun_running
	/tmp/create_swap.sh &

	if [ "X${HARDWARE}" = "Xsun8i" -o "X${HARDWARE}" = "Xsun7i" ]; then
		adjust_sunxi_settings
	fi

	# pine64 temp workaround
	if [ "X${HARDWARE}" = "Xsun50iw1p1" ] && [ -z "$(grep ethaddr /boot/uEnv.txt)" ] && [ -f "/sys/class/net/eth0/address" ]; then
		echo "ethaddr=$(cat /sys/class/net/eth0/address)" >> /boot/uEnv.txt
	fi

	update-rc.d -f firstrun remove >/dev/null 2>&1
	sed -i 's/allow-hotplug\ eth0/auto eth0/' /etc/network/interfaces.default
	rm /tmp/firstrun_running
} # main

main