#!/bin/bash

templateToClone=natty-minimal
vmName=`mktemp -u container-XXXX`
vmPath=/btrfs/vms

if [ "x`which ssft.sh`" = "x" ]; then
	echo "Cannot access ssft library: quitting."
	exit 1
fi
source ssft.sh
[ -n "$SSFT_FRONTEND" ] || SSFT_FRONTEND="$(ssft_choose_frontend)"


if [ $UID -ne 0 ]; then
	echo 'Must be run as root!'
	# Attempt to fire up authentication dialog
	# This should probably be done with polkit but that looks complicated
	if [ "x`which kdesu`" != "x" ]; then
		exec kdesu $0
	elif [ "x`which kdesudo`" != "x" ]; then
		exec kdesudo $0
	else
		exit 1
	fi
fi

# Create temp vm
echo -ne '\n'$templateToClone | lxc-btrfs-clone create -n "$vmName"

# Run temp vm in background screen session
screen -dmS "lxc-$vmName" lxc-start -n "$vmName"

# Wait for VM to start
lxc-wait -n "$vmName" -s RUNNING

# konsole doesn't work because the PID returned isn't the 
# one that owns the resulting konsole session
#konsole --new-tab -e screen -r lxc-$vmName &

# Connect to VM screen session
# Nice big font for presentations
xterm -fg white -bg black -fa Monospace -fs 12 -e screen -r lxc-$vmName &

consolePID=$!

# Three ways to destroy VM:
# 1) VM is stopped
# 2) The spawned window is closed
# 3) This script is killed

while sleep 1; do 
	# Check VM status
	vmStatus=`lxc-info -n "$vmName" | sed 's/.* \([A-Z]*\)$/\1/'`
	if [ "$vmStatus" != "RUNNING" ]; then
		break
	fi

	# Check spawned window still exists
	ps $consolePID > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		break
	fi
done

ssft_select_single "Save VM?" "Would you like to save the virtual machine or destroy it?" \
	"Destroy the VM" "Save the VM for later use"
ssftReturn=$?

# If conainer is running, stop it
vmStatus=`lxc-info -n "$vmName" | sed 's/.* \([A-Z]*\)$/\1/'`
if [ "$vmStatus" = "RUNNING" ]; then
	lxc-stop -n "$vmName"
fi

if [ $ssftReturn -ne 0 -o "$SSFT_RESULT" = "" -o "$SSFT_RESULT" = "Destroy the VM" ]; then 
	# Wait for VM to stop
	lxc-wait -n "$vmName" -s STOPPED

	# Destroy temp vm
	lxc-destroy -n "$vmName"
	btrfs subvolume delete "$vmPath/$vmName"

elif [ "$SSFT_RESULT" = "Save the VM for later use" ]; then 
	SSFT_RESULT=""
	while [ "x$SSFT_RESULT" = "x" ]; do
        # TODO: cancel doesn't work!
		SSFT_DEFAULT="$vmName" ssft_read_string "Enter VM name" "Please enter a name for this VM"
		ssftReturn=$?
	done

	# Wait for VM to stop
	lxc-wait -n "$vmName" -s STOPPED
	if [ $ssftReturn -eq 0 -a "x$SSFT_RESULT" != "x" -a "$vmName" != "$SSFT_RESULT" ]; then
		mv "$vmPath/$vmName" "$vmPath/$SSFT_RESULT"
		mv /var/lib/lxc/"$vmName" /var/lib/lxc/"$SSFT_RESULT"
		sed -i "s%lxc.utsname = $vmName%lxc.utsname = $SSFT_RESULT%" /var/lib/lxc/"$SSFT_RESULT"/config
		sed -i "s%lxc.rootfs = $vmPath/$vmName%lxc.rootfs = $vmPath/$SSFT_RESULT%" /var/lib/lxc/"$SSFT_RESULT"/config
	fi
fi

