#! /bin/sh

set -e

qwdprefix=/var/lib/qemu-web-desktop
include_file=$qwdprefix/include.html
image_list_file=/etc/qemu-web-desktop/machines.conf

case "$1" in
    download)
	mkdir -p $qwdprefix/machines
	cd $qwdprefix/machines

	for i in $(confget -f $image_list_file -q sections) ; do
	    mkdir -p $i
	    u=$(confget -f $image_list_file -s $i url)
	    if [ "$u" ] ; then
		cd $i
		wget -N $u
		cd ..
	    fi
	    vm=$(ls -t $i/* | head -1)
	    if [ -e "$vm" ] ; then
		ln -sf $vm $i
	    fi
	done
	$0 refresh
	;;
    refresh)
	mkdir -p $qwdprefix/snapshots
	chown _qemu-web-desktop $qwdprefix/snapshots
	mkdir -p $qwdprefix/machines
        cd $qwdprefix/machines

	t=$(mktemp $include_file.XXXXXX)
	chmod 644 $t
	for i in $(confget -f $image_list_file -q sections) ; do
	    d=$(confget -f $image_list_file -s $i description)
	    if [ -e $i ] ; then
		echo "<option value='$i'>$d</option>" >> $t
	    fi
	done
	mv $t $include_file
	;;
    *)
	echo "Unknown command $1"
	echo "Usage: $0 controls the availability of virtual machines for the qemu-web-desktop service."
	echo "  The main file to tune is $image_list_file."
	echo "  Entries should contain lines"
	echo "    [name.ext]"
	echo "    description=<blah>"
	echo "  In addition, any line with "
	echo "    url=<link>"
	echo "  will retrieve the given file. "
	echo "  Supported virtual machine formats are: ISO, QCOW2, VDI, VMDK, RAW" 
	echo " "
	echo "$0 download"
	echo "  scan the $image_list_file file for [name.ext] and download them when URL are given."
	echo "  a 'refresh' is then performed. Virtual machine images are stored into $qwdprefix/machines."
	echo " "
	echo "$0 refresh"
	echo "  scan the $image_list_file file, and generate the $include_file that lists"
	echo "  available images to show in the qemu-web-desktop main form."
	exit 1
esac
