#!/bin/bash

### BEGIN INIT INFO
# Provides:          resize2fs
# Required-Start:    $local_fs
# Required-Stop:
# Should-Start:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Resize the root filesystem to fill partition
# Description:
### END INIT INFO

set -e
device="/dev/"$(lsblk -idn -o NAME | grep mmcblk0)
PARTITIONS=$(($(fdisk -l $device | grep $device | wc -l)-1))
device="/dev/"$(lsblk -idn -o NAME | grep mmcblk0)"p"$PARTITIONS
N=/etc/init.d/resize2fs
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)

case "$1" in
  start)		
		if [[ $rootfstype == ext4 && ! -f "/root/.no_rootfs_resize" ]]; then
			/sbin/resize2fs $device >/dev/null 2>&1			
		fi
		if [[ ! -f "/var/swap" ]]; then
			dd if=/dev/zero of=/var/swap bs=1024 count=131072 status=noxfer >/dev/null 2>&1
			chown root:root /var/swap
			chmod 0600 /var/swap
			mkswap /var/swap >/dev/null 2>&1
			swapon /var/swap >/dev/null 2>&1
			if ! grep -q swap /etc/fstab; then echo "/var/swap none swap sw 0 0" >> /etc/fstab; fi 
			if ! grep -q swap /etc/sysctl.conf; then echo "vm.swappiness=0" >> /etc/sysctl.conf; fi 
		fi
		update-rc.d -f resize2fs remove >/dev/null 2>&1
		;;
	*)
		exit 1
		;;
esac

exit 0