#!/bin/sh

set -e

case "$1" in
  prereqs)
    exit 0
    ;;
esac

if ! grep -q ' resize' /proc/cmdline; then
  exit 0
fi

get_variables () {
  set +e # This function does not work as intended with -e
  local_device_setup "$ROOT" "root file system"
  set -e
  ROOT_PART_NAME="$(lsblk -no kname "$DEV")"

  ROOT_DEV_NAME="$(lsblk -no pkname "$DEV")"
  ROOT_DEV="/dev/$ROOT_DEV_NAME"

  ROOT_PART_NUM=$(cat "/sys/block/$ROOT_DEV_NAME/$ROOT_PART_NAME/partition")

  ROOT_DEV_SIZE=$(cat "/sys/block/$ROOT_DEV_NAME/size")
  TARGET_END="$((ROOT_DEV_SIZE - 1))"
  if [ "$TARGET_END" -gt 4294967295 ]; then
    TARGET_END=4294967295
  fi
}

do_resize () {
  if ! parted -m "$ROOT_DEV" u s resizepart "$ROOT_PART_NUM" "$TARGET_END"; then
    return 1
  fi
}

. /scripts/functions
. /scripts/local

log_begin_msg "Resizing root partition..."

get_variables
if [ "$ROOT_PART_NUM" -eq 2 ]; then
  do_resize
else
  log_warning_msg "Resize skipped due to unexpected partition table"
fi

unset ROOT_PART_NAME
unset ROOT_DEV_NAME
unset ROOT_DEV
unset ROOT_PART_NUM
unset ROOT_DEV_SIZE
unset TARGET_END

log_end_msg

exit 0
