#!/bin/sh -e

PREREQ=""

# Output pre-requisites
prereqs()
{
        echo "$PREREQ"
}

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

DISK=mmcblk0
SEP="p"

LOG=/dev/.initramfs/jasper.log
CACHE=/dev/.initramfs/jasper-vfat

touch ${LOG}
mkdir -p ${CACHE}

BOOTPATH=""
PARTITION=""

# we only handle mmc and sdX disk types atm if a UUID is already set we dont want
# to do any action since we assume the system was configured before
[ -z "`grep root=UUID /proc/cmdline`" ] || exit 0
for arg in $(cat /proc/cmdline)
do
    case $arg in
        root=*)
            BOOTPATH=${arg#root=}
            PARTITION=${BOOTPATH#/dev/}
            case $PARTITION in
                mmcblk*)
                    DISK=$(echo ${PARTITION}|sed -e 's/p[0-9]*$//')
                    ;;
                sd*)
                    DISK=$(echo ${PARTITION}|sed -e 's/[0-9]*$//')
                    SEP=""
                    ;;
                *)
                    echo "E: Jasper error, can not hanlde this disk type"
                    exit 1
                    ;;
            esac
            ;;
    esac
done

# We save the vfat contents because we adjust the CHS gemoetry to match the SD card,
# MLO/u-boot wont work without re-formatting the vfat with the new values
cache_vfat()
{
    mount -t tmpfs -o mode=0755 none ${CACHE}
    mkdir -p /mnt
    mount -t vfat /dev/${DISK}${SEP}1 /mnt
    cp -a /mnt/* ${CACHE}/
    umount /dev/${DISK}${SEP}1
}

# Format the new vfat and write the cached content back in the right order
write_vfat()
{
    # TODO: find a better LABEL and add it to list of hidden partitions in udisk
    /sbin/mkdosfs -n "SERVICEV001" -F 32 /dev/${DISK}${SEP}1
    mount /dev/${DISK}${SEP}1 /mnt
    for file in MLO boot.scr u-boot.bin uImage uInitrd; do
        cp ${CACHE}/$file /mnt/${file}
        sync
    done
    umount ${CACHE}
    umount /mnt
}

# The actual resizing function
resize_partitions()
{
    # Get size in blocks of first partition and cylinder count
    SIZE_P1=`LANG=C /sbin/fdisk -l /dev/${DISK} | grep ${DISK}${SEP}1 | awk '{print $4}'`
    DISKSIZE=`LANG=C /sbin/fdisk -l /dev/${DISK} | grep Disk | awk '{print $5}' | tr -d '\n'`
    CYLS=$(($DISKSIZE/255/63/512))
    sync
    # Enlarge the OS partition to fill the rest of the disk, we need to maintain
    # the new CHS geometry for the bootloader
    /sbin/sfdisk -H 255 -S 63 -C ${CYLS} --no-reread -D -q /dev/${DISK} <<EOF >>${LOG} 2>&1
,$SIZE_P1,c,*
,,,-
EOF
}

echo "Caching vfat content in ${CACHE} ..." >>${LOG}
cache_vfat >>${LOG} 2>&1

echo "Resizing root partition ..." >>${LOG}
resize_partitions

echo "Re-writing vfat partition ..." >>${LOG}
write_vfat >>${LOG} 2>&1

# Give some info to the user TODO: create plymouth output
echo "Resizing root filesystem. Please wait, this will take a moment ..."
echo "Resizing root filesystem ..." >>${LOG}
# little workaround for wrong clocks
mount /dev/${DISK}${SEP}2 /root >>${LOG} 2>&1
umount /root >>${LOG} 2>&1

printf "Checking filesystem before resizing..."
/sbin/e2fsck -fy /dev/${DISK}${SEP}2 >>${LOG} 2>&1 || true
echo " Done."
pass=1
iter=0
LANG=C /sbin/resize2fs -p /dev/${DISK}${SEP}2 2>&1 | while read -n 1 input; do
    char=$(echo $input|sed 's/[)(]//')
    if [ "${char}" = "X" ];then
        if [ "${iter}" = "100.0" ];then
            iter=0
            pass=$(($pass+1))
            echo >>${LOG}
        fi  
        iter=$(echo $iter+2.5|bc)
        printf "\rResizing, pass: %i [%3.0f/100]" $pass $iter
    fi  
    if [ -z "${char}" ]; then
        echo -n " " >>${LOG}
    else
        echo -n "${char}" >>${LOG}
    fi  
done
echo >>${LOG}
echo
echo 1>/dev/.initramfs/jasper-reboot

# Set a new UUID to make sure we're unique in the world
/sbin/tune2fs -U $(uuidgen) /dev/${DISK}${SEP}2 >>${LOG} 2>&1

rm /etc/mtab
rm -rf ${CACHE}
