#!/bin/sh

set -e

help()
{
    echo "
Use:
    $0 imagename size

where size is in bytes with optional unit [K,M,G] and must start with:
    '+' to extend by [+100M]
    '>' at least [>1G]\n
" >&2
}

if [ -z "$1" ] || ! (echo "$2" | grep -qe '^[>+]'); then
    help
    exit 1
fi

if ! [ -w "$1" ]; then
    echo "File $1 does not exists or is not writeable" >&2
    exit 2
fi

filename="$1"
size="${2}"
truncate -s "$size" "$filename"
fsck.ext4 -f "$filename"
resize2fs "$filename"
