#!/bin/bash
bootimg=""
rootimg=""
qemuroot=""
while getopts "b:r:q:" opt; do
    case $opt in
        b)
            bootimg=$OPTARG
            ;;
        r)
            rootimg=$OPTARG
            ;;
        q)
            qemuroot=$OPTARG
            ;;
    esac
done


create_empty_disk()
{
    img_name=$1
    echo "Creating disk image $img_name"
    dd if=/dev/zero of=$img_name bs=4M count=300 > /dev/null
}

create_loopback()
{
    img_name=$1
    device=$(losetup -f)
    sudo losetup $device $img_name
    echo $device
}

get_partition_name()
{
    echo "/dev/mapper/${1##*/}p"$2
}

format_sdcard()
{
    device=$1
    img_name=$2
    system_size="+1100M"
    boot_size="+70M"
    set +e
    mounts=`cat /proc/mounts  | grep "$device" | cut -d' ' -f1`
    set -e
    if [ "$mounts" != "" ];then
        for i in $mounts;
        do
            sudo umount $i -l
        done
    fi

    echo "making partitions on ${device}..."
    set +e
    sleep 1
    sudo fdisk $device > /tmp/log << EOF
n
p
1

$boot_size
n
p
2

$system_size
t
1
c
a
1
w
EOF
    set -e
    #With loop block devices, new partition are not automatically associated to a new loop partition. kpartx do that for us !
    if [[ $device == *"loop"* ]]; then
        sudo losetup -d $device
        sudo kpartx -a $img_name
    fi

    echo "$(get_partition_name $device 1) formatting..."
    part=$(get_partition_name $device 1)
    sudo dd if=$bootimg of=$part > /dev/null

    echo "$(get_partition_name $device 2) formatting... (takes some minutes)"
    part=$(get_partition_name $device 2)
    sudo dd if=$rootimg of=$part > /dev/null
    tmp_dir=$(mktemp -d)
    sudo mount $part $tmp_dir

    sudo cp -r $qemuroot/target/lib/modules/4.9.6/ ${tmp_dir}/lib/modules

    sudo umount $tmp_dir
    rm -r $tmp_dir
}


name=disk.img

create_empty_disk $name
device=$(create_loopback $name)
format_sdcard ${device} ${name}
sudo kpartx -d ${name}

