#!/bin/bash

if [ `whoami` != root ]; then
        echo "this utility must be run from root or using sudo!"
        exit 1
fi

DEBOOTSTRAP_PATH=/mnt/BigDisk/workspace/precise/rootfs/debootstrap

ROOTSTOCK_PATH=/mnt/BigDisk/workspace/precise/rootfs/rootstock

KERNEL_RELEASE=3.2.46-100


####################################
### let us create a new qemu image from scratch!##############
BACKUP_BOOT=${ROOTSTOCK_PATH}/backup-boot
BACKUP_ROOTFS=${ROOTSTOCK_PATH}/backup-rootfs
SD_IMG=${ROOTSTOCK_PATH}/sd.img
IMG_SIZE=2123123200
ARM_CREATE_IMG_SCRIPT=${ROOTSTOCK_PATH}/arm-create-img.sh

############first umount possible mount before rm the image file###################

umount ${ROOTSTOCK_PATH}/boot
umount ${ROOTSTOCK_PATH}/rootfs

rm ${SD_IMG}

${ARM_CREATE_IMG_SCRIPT} ${SD_IMG} ${IMG_SIZE} ${BACKUP_BOOT} ${BACKUP_ROOTFS}
### need to change the owner so that it can run from user mode?
chown nick:nick ${SD_IMG}
######## NEED TO MOUNT THE NEW IMAGE##################

cd ${ROOTSTOCK_PATH};
./arm-mount.sh

#####################################################

#########now copy finished kernel file and create initrd for uboot##################
MOD_INSTALL_PATH=lib/modules

ROOTFS=rootfs

BOOT=boot

SRC_PATH=usr/src/ubuntu-precise

cp -r ${DEBOOTSTRAP_PATH}/${ROOTFS}/${MOD_INSTALL_PATH}/${KERNEL_RELEASE} ${ROOTSTOCK_PATH}/${ROOTFS}/${MOD_INSTALL_PATH}

cp -v ${DEBOOTSTRAP_PATH}/${ROOTFS}/${SRC_PATH}/.config ${ROOTSTOCK_PATH}/${ROOTFS}/boot/config-${KERNEL_RELEASE}

cp -v ${DEBOOTSTRAP_PATH}/${ROOTFS}/${SRC_PATH}/arch/arm/boot/uImage ${ROOTSTOCK_PATH}/${ROOTFS}/boot/uImage-${KERNEL_RELEASE}

cp -v ${DEBOOTSTRAP_PATH}/${ROOTFS}/${SRC_PATH}/arch/arm/boot/uImage ${ROOTSTOCK_PATH}/${BOOT}/uImage

#########################chroot and exec a script to create uInitrd############################
LFS=${ROOTSTOCK_PATH}/${ROOTFS}

mount -v --bind /dev $LFS/dev
mount -vt devpts devpts  $LFS/dev/pts
mount -vt tmpfs shm $LFS/dev/shm
mount -vt proc proc $LFS/proc
mount -vt sysfs sysfs $LFS/sys

chroot ${LFS}  /usr/bin/env -i HOME=/root TERM="$TERM" PS1='\u:\w\$' PATH=/bin:/usr/bin:/sbin:/usr/sbin /bin/bash -c "/arm-initrd.sh ${KERNEL_RELEASE}" --login +h

umount -v $LFS/sys
umount -v $LFS/proc
umount -v $LFS/dev/shm
umount -v $LFS/dev/pts
umount -v $LFS/dev

cp -v ${ROOTSTOCK_PATH}/${ROOTFS}/boot/uInitrd-${KERNEL_RELEASE}  ${ROOTSTOCK_PATH}/${BOOT}/uInitrd
############### now run the qemu###########
cd ${ROOTSTOCK_PATH}
./arm-qemu.sh

