#!/bin/bash
#       Copyright (C) MOXA Inc. All rights reserved.
#       Copyright (C) 2014-2015  Lock Lin <Lock.Lin@moxa.com>
#
#       This software is distributed under the terms of the
#       MOXA License.  See the file COPYING-MOXA for details.
#
#       expand2fs
#               Expand the size of rootfilesystem when first boot.
#

do_expand_rootfs() {
  # Get the starting offset of the root partition
  PART_START=$(fdisk -l $2 | grep ${1} | awk '{printf $2 }')
  [ "$PART_START" ] || return 1
  mount -o remount,rw /
  # Return value will likely be error for fdisk as it fails to reload the
  # partition table because the root fs is mounted
  fdisk $2 <<EOF
p
d
3
n
p


p

w
EOF

partprobe
sleep 1
e2fsck -f $1
sleep 1
resize2fs $1
}

# Get rootfile system partition from cmdline. e.g. /dev/mmcblk0p2
kernel_cmd=$(cat /proc/cmdline)
rootfs_node="${kernel_cmd##*root=}"
rootfs_node="${rootfs_node%% *}"
root_node="${rootfs_node%%p2}"

# expand for overlayfs p3
rootfs_node="${root_node}p3"
# rootfs_node="${root_node}p2"
do_expand_rootfs $rootfs_node $root_node
sync
echo "***************************************************" > /dev/ttyS0
echo "*  The rootfilesystem is expanded successfully !  *" > /dev/ttyS0
echo "*      This device is going to reboot NOW !!!     *" > /dev/ttyS0
echo "***************************************************" > /dev/ttyS0
