#!/bin/sh -e

PREREQ="fixrtc"

# 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=""
MYECHO="echo "

if [ -x /bin/plymouth ] && plymouth --ping; then
	MYECHO="plymouth message --text="
fi

# 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=""
                    ;;
                *)
                    $MYECHO"E: Jasper error, can not handle this disk type"
                    exit 1
                    ;;
            esac
            ;;
    esac
done

export ROOTDEV="/dev/${DISK}${SEP}"

# 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 ${ROOTDEV}1 /mnt
    cp -a /mnt/* ${CACHE}/
    umount ${ROOTDEV}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 ${ROOTDEV}1
    mount ${ROOTDEV}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
}

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

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

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

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

$MYECHO"Checking filesystem before resizing..."
/sbin/e2fsck -fy ${ROOTDEV}2 >>${LOG} 2>&1 || true
$MYECHO"Resizing, please wait..."
pass=1
iter=0
LANG=C /sbin/resize2fs -p ${ROOTDEV}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 1>/dev/.initramfs/jasper-reboot

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

rm -rf ${CACHE}
