#!/bin/sh
# options: hostname pool installcd
# so, for example:
# createvm.sh qemufaiserver tearoff fai_cd.iso

# provisioning takes place in two steps: creating a disk image, and first boot/reboot.
# step 1 does not require network or knowlege about the network resources being provisioned to the VM.
# the results of step 1 are cacheable across provisions.
# step 2 is 'runtime'.
# after step 2 is done:
# port forwards allocated by the pool should be in place.

SELF_NAME=$(basename "$0")

# debugging flag. use '1' for verbose
if [ -z "$DEBUG" ]; then
	DEBUG=0
else
	echo >&2 "DEBUG is $DEBUG"
fi

# Function to display how to use the program in case you forgot
usage() {
	echo >&2 "$0: Invalid arguments."
	echo >&2 "Usage: $0 <vm_hostname> <pool_name> <install_iso>"
	echo >&2 "       <vm_hostname> - Name of host type to build from the installation ISO,"
        echo >&2 "                       must defined in HOSTNAME_OPTS for this pool."
	echo >&2 "       <pool_name>   - Name of the virtual machine pool to carve out the virtual machine from."
	echo >&2 "       <install_iso> - Name of the ISO file to install the virtual machine with."

	return
}

# OPTIND=1
unset -v target_hostname target_poolfile target_iso target_iso_sha1 target_disksize
while getopts ":h:p:i:s:" OPTION
do {
	case "$OPTION" in
	 (\?)
		printf '%s: Unknown option: -%s\n' "$SELF_NAME" "$OPTARG" >&2
		usage
		exit 1
		;;
	 (:)
		printf '%s: Missing argument to -%s option\n' \
			"$SELF_NAME" "$OPTARG" >&2
		usage
		exit 1
		;;
	 (h)
		target_hostname=$OPTARG
		;;
	 (p)
		target_poolfile=$OPTARG
		;;
	 (i)
		target_iso="$OPTARG"
		;;
	 (s)
		target_disksize=$OPTARG
		;;
	 (*)
		printf '%s: Unknown option provided by getopts; OPTION=%s\n' \
			"$SELF_NAME" "$OPTION" >&2
		exit 127
		;;
	esac
}
done
shift "$((OPTIND - 1))"

# Compatibility: Take some option-arguments even when their option is not
# provided.
if [ ! "${target_hostname+SET}" ]; then
{
	if [ $# -lt 1 ]; then
	{
		printf '%s: vm_hostname was not specified.\n' "$SELF_NAME" >&2
		usage
		exit 1
	}
	fi

	target_hostname=$1
	shift 1
}
fi

if [ ! "${target_poolfile+SET}" ]; then
{
	if [ $# -lt 1 ]; then
	{
		printf '%s: pool_name was not specified.\n' "$SELF_NAME" >&2
		usage
		exit 1
	}
	fi

	target_poolfile=$1
	shift 1
}
fi

if [ ! "${target_iso+SET}" ]; then
{
	if [ $# -lt 1 ]; then
	{
		printf '%s: install_iso was not specified.\n' "$SELF_NAME" >&2
		usage
		exit 1
	}
	fi

	target_iso="$1"
	shift 1
}
fi

# FIXME: this isn't working as intended. i'd like to allow this to be specified manually by prefixing at a bash prompt.
if [ -z "$CONFDIR" ] ; then
    CONFDIR=/etc/createvm
fi

# read the configuration file
. $CONFDIR/createvm.conf

# source the pool definitions, or 'provisioning group'
. $POOL_DIR/$target_poolfile

target_pool=$POOL_UID

# First, perform sanity checks.

# make sure the installcd exists.
if [ ! -f "$ISO_DIR/$target_iso" ] ; then
    {
	echo >&2 "$0: Install cd $target_iso not found; aborting."
	exit 1
    }
fi;

# Make sure there is a directory for dropping our vm tracking files in.
if [ ! -w $MGMT_DIR/running_VMs/ ]; then
    {
	echo >&2 "$0: Problem writing to $MGMT_DIR/running_VMs/. Are you root?"
	exit 1
    }
fi;

# Make sure there is a directory for managing preseeds.
if [ ! -w $MGMT_DIR/preseeds/ ]; then
    {
	echo >&2 "$0: Problem writing to $MGMT_DIR/preseeds/. Make sure directory exists, and is writeable"
	exit 1
    }
fi;

# Gather the sha1sum of the installation CD, as a fingerprint.
target_iso_sha1=$(sha1sum "$ISO_DIR/$target_iso"|cut -d' ' -f1)

# pick a default disk size, from the config file.
if [ -z "$target_disksize" ]; then
    target_disksize=$default_disk_size
fi

# Grab a lockfile.
lockfile $LOCK_DIR/$LOCKFILE

# See if the pool has the resources for another VM.
VM_AVAILABLE=$(pool_check_available $target_hostname $target_pool $target_disksize)

# The VM is available, let us attempt to allocate it.
if [ "$VM_AVAILABLE" = "0" ]; then
    {
	[ "$DEBUG" = "1" ] && echo >&2 "Attempting VM allocation."
        # perform allocation of resources.
	VM_UID=$(pool_vm_allocate $target_hostname $target_pool $target_disksize $target_iso_sha1)
	[ "$DEBUG" = "1" ] && echo "VM UID Returned: $VM_UID"
    }
fi

# Assign a unique name to our VM. This is the name of the directory we place all the vm specific files into, as well.
VMNAME=$target_hostname-$target_pool-$VM_UID

# use a different name for the screen sessions, without the hostname.
VMSCREEN=preseed-$target_pool-$target_hostname-$VM_UID

# release the lockfile.
rm -f $LOCK_DIR/$LOCKFILE

# check to see if we successfully allocated a VM instance.
if [ -z "$VM_UID" ]; then
    {
	echo >&2 "$0: VM allocation failure, one more more resources are not available. Aborting. error=$VM_AVAILABLE"
	exit 1;
    }
fi

# check to make sure we're not about to clobber a real VM..
if [ -d "$VM_DIR/$VMNAME" ]; then
    {
	echo >&2 "$0: A startup directory appears to already be set up for $VMNAME at $VM_DIR/$VMNAME. Aborting."
	exit 1;
    }
fi

PRESEEDDIR=$PRESEED_DIR/$target_hostname-$target_iso_sha1-$target_disksize

# FIXME: release the lock while cloning a VM from a preseed.

# Decide if we have a cached VM ready to go.
# if there is a pre-built VM, clone the new VM into place
if [ ! -d "$PRESEEDDIR" ]; then
    {
# grab the lockfile.
	lockfile $LOCK_DIR/$LOCKFILE

# check to see if another createvm is creating a pressed for this vm..
	if [ -f $MGMT_DIR/preseeds/$VMNAME ]; then
	    {
# if so...

# release the lockfile.
		rm -f $LOCK_DIR/$LOCKFILE
		
		[ "$DEBUG" = "1" ] && echo >&2 "another VM is provisioning. waiting.."
		while ( -f $MGMT_DIR/preseeds/$VMNAME )
		do {
# wait for the other createvm to do our work for us..
			sleep 30
		    }
		done;
		
# re-grab the lockfile.
		lockfile $LOCK_DIR/$LOCKFILE
		
		[ "$DEBUG" = "1" ] && echo "vm provisioned by other createvm process."
	    }
	else
	    {
# if not, mark down that we're going to create a new VM
		touch $MGMT_DIR/preseeds/$VMNAME

# release the lockfile.
		rm -f $LOCK_DIR/$LOCKFILE
		
		hostname=`hostname`

# create the container directory
		mkdir -p $PRESEEDDIR
		
# create the startup-kvm.sh script
		cp $TEMPLATE_DIR/startup-kvm.sh $PRESEEDDIR/

# create startup variables, for the install
# FIXME: drop a libvirt compatible xml file here.

# get the variables the network expects to pass into startup-kvm.sh.
		NETVARS=$(pool_export_startup_net_variables_preseed $target_hostname $target_pool $VM_UID)

# copy the disk from the preseed disk
		BOOTHD=/dev/$target_pool/$target_hostname-$target_pool-$target_iso_sha1-$target_disksize
		
# pass values to startup-kvm.sh
		cat  > $PRESEEDDIR/startup-variables.sh <<EOF
KVM_BIN=$KVM_BIN
CD="$ISO_DIR/$target_iso"
MEM=$preseed_ram
$NETVARS
BOOTHD=$BOOTHD
EOF

# create stub ifup and ifdown scripts.
		echo '#!/bin/sh' > $PRESEEDDIR/ifup-bridge.sh
		echo '#!/bin/sh' > $PRESEEDDIR/ifdown-bridge.sh
		chmod 755 $PRESEEDDIR/ifup-bridge.sh $PRESEEDDIR/ifdown-bridge.sh

# install the system from its FAI CD.
		cp  $TEMPLATE_DIR/init_fai_grub2.tt $PRESEEDDIR/
		cat > $PRESEEDDIR/init_vm.tt <<EOF
#var hostname $hostname
#var USERNAME $USERNAME
#var USERPASSWD $USERPASSWD
#var PRESEEDDIR $PRESEEDDIR
#var VMSCREEN $VMSCREEN
#var target_hostname $target_hostname

#read $TEMPLATE_DIR/init_fai_grub2.tt

#run local bash
EOF
		# use screen, to disappear the console during the install.
		screen -D -m -S preseed-$VMNAME /usr/games/tt++ $PRESEEDDIR/init_vm.tt

# grab a lockfile. for how many of which VMs we have going.
		lockfile $LOCK_DIR/$LOCKFILE
		
# remove the lock on creating this preseed.
		rm -f $MGMT_DIR/preseeds/$VMNAME
		
# release the lockfile.
		rm -f $LOCK_DIR/$LOCKFILE
	    }
	fi
    }
fi

# The PRESEED has been built we either just finished building it or we are cloning
vm_lv=$target_hostname-$target_pool-$VM_UID
preseed_lv=$target_hostname-$target_pool-$target_iso_sha1-$target_disksize
success=$(lvm_check_lv $target_pool $vm_lv $target_disksize)
if [ $? -ne 0 ]; then
	# We have finished building the preseed, but do not have a working clone
	BOOTHD=$(lvm_copy_lv $target_pool $preseed_lv $vm_lv)
fi

# copy our stage1 to its running directory.
# FIXME: this should basically be an lvcopy.
rsync -arqSPX $PRESEEDDIR/ "$VM_DIR/$VMNAME"

# get the variables the pool needs to pass into startup-kvm.sh
NETVARS=$(pool_export_startup_variables $target_hostname $target_pool $VM_UID)

# ask the pool to write out bridge config files
pool_write_interfaces $target_hostname $target_pool $VM_UID

# pass values to startup-kvm.sh
cat > "$VM_DIR/$VMNAME/startup-variables.sh" <<EOF
KVM_BIN=$KVM_BIN
CD="$ISO_DIR/$target_iso"
$NETVARS
EOF
