#!/bin/sh
set -e

# No resizing with less than 10k unused blocks
BLOCKS_FREE=$(/usr/bin/awk '/sda$/ {blocks = $3} /sda\d/ {blocks -= $3} END {print blocks}' /proc/partitions)
[ ${BLOCKS_FREE} -lt 10240 ] && exit 0

# Resize physical partition
# Force busybox fdisk as util-linux fdisk breaks subsequent partx command
cat <<EOF | /bin/busybox fdisk /dev/sda || /bin/true
d
2
n
p
2


t
2
8e
w
EOF

# Re-read partition table
/usr/sbin/partx -u /dev/sda2

# Resize dmcrypt and LVM PV
/sbin/cryptsetup resize system
/sbin/pvresize /dev/mapper/system

# Create swap if it doesn't exist
if [ ! -e /dev/vg0/swap ]; then
    /sbin/lvcreate -L 4G vg0 -n swap
    /sbin/mkswap /dev/vg0/swap
fi

# Extend LV and underlying filesystem
/sbin/lvextend -l +100%FREE vg0/root
/usr/sbin/resize2fs /dev/vg0/root
