#!/bin/bash

#ROOT_PARTITION=`mount | grep " on / type" | awk '{ print $1 }'`
ROOT_PARTITION=$(mount | sed -n 's|^/dev/\(.*\) on / .*|\1|p')

if [ "$ROOT_PARTITION" = "" ]; then
  echo "Can't find root device...\n";
  exit
fi

ROOT_PARTITION="/dev/$ROOT_PARTITION"
ROOT_DEVICE=${ROOT_PARTITION::-1}

PART_NUM=1

#LAST_PART_NUM=$(parted $ROOT_DEVICE -ms unit s p | tail -n 1 | cut -f 1 -d:)
PART_START=$(parted $ROOT_DEVICE -ms unit s p | grep "^${PART_NUM}" | cut -f 2 -d: | sed 's/[^0-9]//g')

fdisk $ROOT_DEVICE <<EOF
p
d
$PART_NUM
n
p
$PART_NUM
$PART_START

p
w
EOF

# this will make the script run_pos_new.sh to resize the fs and reboot
# the machine again
echo -n $ROOT_PARTITION > /.resized_partition

# make sure root device is bootable
if [ "$ROOT_DEVICE" != "" ]; then
  IS_BOOTABLE=`fdisk --list $ROOT_DEVICE | tail -1 | grep "*"`

  if [ "$IS_BOOTABLE" = "" ]; then
    (
    echo a
    echo w
    ) | fdisk $ROOT_DEVICE
  fi
fi

reboot

