#!/bin/bash

[ -f '@sysconfdir@/setupkey.conf' ] && . '@sysconfdir@/setupkey.conf'

[ -z "$FS_SIZE" ] && FS_SIZE=900

[ -z "$PACKAGES" ] && PACKAGES="yum dos2unix bash dracut device-mapper hp-health hpacucli hponcfg libxslt libstdc++.i686 hp-scripting-tools"

[ -z "$DATA" ] && DATA=$(PWD)

if [ ! -d "$DATA/customized" ]; then
	echo "Cannot find the customized files used to capture and deploy configurations. Exiting now."
	exit 1
fi

TMPDIR=$(mktemp -d)
FS_FILE=$TMPDIR/ext3fs.img
DRACUT=$(which dracut)
DRACUT_OPT="-a dmsquash-live -o plymouth -v"

#cd $TMPDIR

mkdir $TMPDIR/{root,rpms}

[ -f $FS_FILE ] && rm -rf $FS_FILE

dd if=/dev/zero of=$FS_FILE bs=1M count=$FS_SIZE

if [ ! $? -eq 0 ]; then
	echo "Was not able to create a $FS_FILE ${FS_SIZE}MB file."
	rm -rf $TMPDIR
	exit 1
fi

LO_DEVICE=$(losetup -f)

losetup $LO_DEVICE $FS_FILE

if [ ! $? -eq 0 ]; then
	echo "Was not able to attach $FS_FILE to any loopback device."
	rm -rf $TMPDIR
	exit 2
fi

cleanup() {
	echo "Removing $TMPDIR"
	rm -rf $TMPDIR
}

mkfs.ext3 -m0 -L root_fs $LO_DEVICE
mount -o loop $LO_DEVICE $TMPDIR/root

sync

echo $KERNEL

mkdir $TMPDIR/root/{tmp,dev,sys,proc,mnt}
mkdir -p $TMPDIR/root/var/lib/rpm

rpm --root $TMPDIR/root --initdb

mkdir -p $TMPDIR/root/etc/{yum.repos.d,pki}

mount -B /dev $TMPDIR/root/dev
mount -B /proc $TMPDIR/root/proc
mount -B /sys $TMPDIR/root/sys

cp -a /etc/pki/rpm-gpg $TMPDIR/root/etc/pki
cp /etc/resolv.conf $TMPDIR/root/etc/
cp /etc/yum.conf $TMPDIR/root/etc/yum.conf
cp /etc/yum.repos.d/* $TMPDIR/root/etc/yum.repos.d/
touch $TMPDIR/root/etc/fstab
#cp $(dirname $RPM_LIST)/hp-scripting-tools-8.70-52.rhel6.i386.rpm $TMPDIR/root/tmp/
#cp $DATA/hp-scripting-tools-8.70-52.rhel6.i386.rpm $TMPDIR/root/tmp/

yum --installroot=$TMPDIR/root/ -y  install $PACKAGES
yum --installroot=$TMPDIR/root/  clean all

#tar -C $TMPDIR/root -xvf $(dirname $RPM_LIST)/ssstk.tar
#tar -C $TMPDIR/root -xvf ./ssstk.tar
cp -av $DATA/customized/* $TMPDIR/root

KERNEL=$(chroot $TMPDIR/root rpm -q kernel)
KERNEL_VERSION=${KERNEL##kernel-}
echo "Installed kernel is $KERNEL_VERSION"

chroot $TMPDIR/root depmod -a $KERNEL_VERSION
chroot $TMPDIR/root $DRACUT $DRACUT_OPT /boot/initramfs.img $KERNEL_VERSION

cp $TMPDIR/root/boot/initramfs.img $DATA
cp $TMPDIR/root/boot/vmlinuz-$KERNEL_VERSION $DATA/vmlinuz

umount $TMPDIR/root/sys
umount $TMPDIR/root/proc
umount $TMPDIR/root/dev

umount $TMPDIR/root

sleep 1

echo "Releasing $LO_DEVICE"
losetup -dv $LO_DEVICE

mv $FS_FILE $DATA

cleanup
