#!/bin/sh

# provisioning pool definition file for a pool of tear-off VMs.
# provides functions for killVM, createvm.sh, and others.

# VARIABLES INHERITED:
# MGMT_DIR -- the directory to create our lockfiles in.
# CONF_DIR -- the directory to find our config file in.
# HELPER_DIR -- the directory to find the resource allocation helper scripts in.

# VARIABLES EXPORTED:
# POOL_UID -- the UID of this pool.

#############
# pool name #
#############

POOL_UID=tearoff

# inherit config
. $CONFDIR/tearoff.conf

#bring in the disk allocator
. $HELPER_DIR/pool_lvm.sh

# bring in the bridge allocator
. $HELPER_DIR/pool_bridge.sh

# bring in the ip block allocator
. $HELPER_DIR/pool_ipblocks.sh

# bring in the ip port forward allocator
. $HELPER_DIR/pool_ipport.sh

# bring in the dhcp service allocator
. $HELPER_DIR/service_dhcp.sh

# bring in the dns service allocator
. $HELPER_DIR/service_dns.sh

# pool_check_available()
# can the provisioning pool handle the addition of another VM of this type?
# arguments:
# $1 == image name of VM requested.
# $2 == pool VM is requested to be allocated out of.
# $3 == disk size of the VM requested.

# returns 0 in case of valid input
# echoes 0 if resources are available, other values otherwise.
pool_check_available() {
    pool_size=$TOTALDISKSIZE
    vm_name=$1
    pool_name=$2
    vm_disksize=$3

    for each in $HOSTNAME_OPTS; do
	{
	    if [ "$each" = "$1" ]; then
		{
		    FOUNDHOSTNAME=1;
		    POOL_VMS=$(find $MGMT_DIR/running_VMs/ $MGMT_DIR/preseeds/ -name "*-$each-*" | wc -l)
		    if [ $POOL_VMS = NO_MACHINES ] ; then
			{
			    echo "1";
			    return 0;
			}
		    fi
		}
	    fi
	}
    done;
    if [ -z "$FOUNDHOSTNAME" ]; then
	{
            echo >&2 "ERROR: Hostname \`$1' is not allowed in pool \`$2' (check /etc/createvm/$2.conf)."
	    echo "2";
	    return 1;
	}
    fi
    if ! lvm_available $pool_name $pool_size $vm_disksize ; then
	    echo >&2 "ERROR: disk resources not available for VM $vm_name in pool $pool_name with size $pool_size and disk size of $vm_disksize."
	    return 1

    fi
    if [ ! $(ipblock_available) ]; then
	{
	    echo >&2 "WARNING: IP block is unavailable." 
	    echo "3";
	    return 0;
	}
    fi
    if [ ! $(bridge_available) ]; then
	{
	    echo >&2 "WARNING: Bridges unavailable." 
	    echo "4";
	    return 0;
	}
    fi
    for each in $PORTS_FORWARDED; do
	{
	    FORWARD=$(ipport_available ${each}00 ${each}99)
	    if [ "$FORWARD" != "0" ]; then
		{
		    echo "5";
		    return 0;
		}
	    fi
	}
    done;
    echo "0";
    return 0;
}

# allocate resources for the VM. in reality, detect/avoid conflicts, and touch lock files.
# required to touch $MGMT_DIR/running_VMs/$hostname-$pool-$instance
# $1 == image name of box requested.
# $2 == network box is requested to be brought online in.
# $3 == vm disk size
# $4 == iso file of image
# $5 == sha1 hash of iso image
# returns a UID assigned to this VM.
pool_vm_allocate() {
pool_name=$2
pool_size=$TOTALDISKSIZE
vm_hostname=$1
vm_disksize=$3
iso_name=$4
iso_sha1=$5

# allocate per-pool resources here

# alocate one IP block, attached to one bridge, with dhcp and dns.
    BRIDGE=$(bridge_find $pool_name 1)
    if [ -z "$BRIDGE" ]; then
	{
	    result=$(bridge_allocate $pool_name 1)
	}
    fi;
    IPBLOCK=$(ipblock_find $pool_name 1)
    if [ -z "$IPBLOCK" ]; then
	{
	    result=$(ipblock_allocate $pool_name 1)
# write out a dhcp range fragment
	    result=$(dhcp_allocate $pool_name 1 $NO_MACHINES 0)
# write out required dns fragments
	    result=$(dns_allocate $pool_name)
	}
    fi

# come up with a unique number for the machine.
    success=1;
    for each in $(seq -s " " 1 $NO_MACHINES)
    do {
	    if ( [ ! -f $MGMT_DIR/preseeds/*-$pool_name-$each ] && [ ! -f $MGMT_DIR/running_VMs/*-$pool_name-$each ] ) ; then
		{
		    VM_UID=$each
		    success=0;
		    break;
		}
	    fi
	}
    done;

# allocate any per-VM resources here
    if [ -z $VM_UID ] ; then
	    echo >&2 "ERROR: VM_UID is empty!  Cannot create LV."
	    return 1
    fi
# time to get the disks
    if ! lvm_allocate_disk $pool_name $pool_size $vm_hostname $vm_disksize $iso_name $iso_sha1 $VM_UID; then
	    echo >&2 "ERROR: Failed to allocate disks for the VM $vm_name with size $vm_disksize in pool $pool_name with requested size $pool_size"
	    return 1
    fi

# use the hostname and vm_uid plus a character as the portfw UID.
# this one is for port 22 (ssh) forwarding.
    for each in $PORTS_FORWARDED; do
	{
	    if [ -z "$PORTUID" ] ; then
		PORTUID=1
	    else
		PORTUID=$(($PORTUID+1))
	    fi
	    result=$(ipport_allocate $POOL_UID $1 ${VM_UID} $1${VM_UID}${PORTUID} $each ${each}00 ${each}99)
	    if [ $? != 0 ]; then
		{
		    echo "";
		    return 1;
		}
	    fi
	}
    done;

    if [ $success ]; then
	{
	    touch $MGMT_DIR/running_VMs/$1-$pool_name-$VM_UID;
	    echo $VM_UID;
	    return 0;
	}
    fi
    
# if we got here, finding a UID for the VM failed. too many VMs started?.
    echo "";
    return 1;
}

# called by de-allocation script,
# when the user wants our VM to die. 
# $1 == image name of box requested
# $2 == pool machine is allocated out of
# $3 == unique identifier given to VM
pool_vm_deallocate() {
    pool_name=$2
    vm_name=$1
    VM_UID=$3
    LVNAME=$1-$2-$3
#Test to see if there is a screen session running for this vm
    TEST=`screen -ls | grep "$1-$2-$3	"`
    if [ -n "$TEST" ]; then
	{
	    echo "Aborting. There is currently a screen for $1, and we don't know how to kill it."
	    exit 1
	}
    else
	{
# de-allocate disk space
	   if ! lvm_destroy_lv $pool_name $LVNAME ; then
		   echo "WARNING: Could not remove the LV $pool_name/$LVNAME"
	   fi
# destroy container directory
	    rm -rf $VM_DIR/$1-$2-$3/
# destroy vm-is-allocated lock file
	    rm -f $MGMT_DIR/running_VMs/$1-$2-$3
# destroy the port forwards.
	    for each in $PORTS_FORWARDED; do
		{
		    if [ -z "$seq" ]; then
			seq=1;
		    else
			seq=$(($seq+1))
		    fi
		    ipport_deallocate $2 ${1}${3}$seq
		}
	    done;

# check to see if any other VMs in our group are running
	    POOL_VMS=$(find $MGMT_DIR/running_VMs/ $MGMT_DIR/preseeds/ -name "*-$2-*")
	    if [ -z "$POOL_VMS" ]; then
		{
# destroy resources owned by the pool, not the VMs.
		    bridge_deallocate $2 1
		    ipblock_deallocate $2 1
		    dns_deallocate $2 1
		    dhcp_deallocate $2 1
		}
	    fi
	}
    fi
}

# export the networking and memory related variables that go in startup-kvm-variables.sh during runtime.
# $1 == image name of box requested
# $2 == network box is requested to be brought online in.
# $3 == VM Unique Identifier.
pool_export_startup_variables() {
    echo MEM=384
    echo MAC=\"$(pool_mac_from_uid $3)\"
    echo NICMODEL=rtl8139
    # use the netup and netdown scripts in the vm's management directory.
    echo NETUPSH=./ifup-bridge.sh
    echo NETDOWNSH=./ifdown-bridge.sh
}

# export the networking related variables that go in startup-kvm-variables.sh during preseed generation.
# $1 == image name of box requested
# $2 == network box is requested to be brought online in.
# $3 == VM Unique Identifier.
pool_export_startup_net_variables_preseed() {
    echo MAC=\"$(pool_mac_from_uid $3)\"
    echo NICMODEL=rtl8139
    # FIXME: there is no reason to have real bridge attachment in the preseed; make this a dummy.
    # use the netup and netdown scripts in the vm's management directory.
    echo NETUPSH=./ifup-bridge.sh
    echo NETDOWNSH=./ifdown-bridge.sh
}


# given the mac address of a vm in this pool, return the UID.
# $1 == mac address
pool_uid_from_mac() {
    echo "$1" | sed -n "s/.*:/ibase=16;/p" | bc | tr -d "\n"
    return 0
}

# given the UID of a vm in this pool, return the MAC address.
# $1 == UID
pool_mac_from_uid() {
    echo -n "52:54:00:12:35:"
    echo "obase=16;$1" | bc | tr -d "\n"
    return 0
}

# write out the bridge configuration script(s) to the VM's container directory.
# assume the IP of the host machine on the bridge is going to be *.*.*.1.
# $1 == image name of box requested
# $2 == network box is being brought online in.
# $3 == VM Unique Identifier.
pool_write_interfaces() {
    cp $TEMPLATE_DIR/ifup-bridge.sh $VM_DIR/$1-$2-$3/
    cp $TEMPLATE_DIR/ifdown-bridge.sh $VM_DIR/$1-$2-$3/
    BRIDGE="$(bridge_find $2 1)"
    BRIDGEIP="$(ipblock_find $2 1).1"
    MGMTDIR=$MGMT_DIR
# now, a variable fragment for the bridge script.
    cat > $VM_DIR/$1-$2-$3/ifup-bridge-variables.sh <<EOF
BRCTL=$BRCTL
BRIDGE=$BRIDGE
BRIDGEIP=$BRIDGEIP
MGMT_DIR=$MGMTDIR
USEDHCP=0
USEDNS=0
EOF
}
