#!/bin/sh
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2010  Rafal Wojtczuk  <rafal@invisiblethingslab.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
#

SHARE_DIR=/var/run/qubes
function do_new()
{
	FILE=$SHARE_DIR/pendrive.$2
	truncate -s 1G $FILE  || exit 1
	vmname=$(xenstore-read /local/domain/$1/name)
	mkfs.vfat -n "$vmname" $FILE || exit 1 
	xm block-attach $1 file:/$FILE /dev/xvdg w || exit 1
}

function do_umount()
{
	xm block-detach $1 /dev/xvdh || exit 1
	rm $SHARE_DIR/pendrive.$2
}

function do_send()
{
	FILE=$SHARE_DIR/pendrive.$3
	vmname=$(xenstore-read /local/domain/$1/name)
	xenstore-write /local/domain/$2/qubes_blocksrc $vmname
	xenstore-write /local/domain/$2/qubes_transaction_seq "$4"
	xm block-detach $1 /dev/xvdg || exit 1
	xm block-attach $2 file:/$FILE /dev/xvdh w || exit 1
}
export PATH=$PATH:/sbin:/usr/sbin
if [ $# -lt 1 ] ; then
	echo args missing ?
	exit 1
fi
if [ "$1" = "new" ] ; then
	if ! [ $# = 3 ] ; then
		echo new requires 2 more args 
		exit 1
	fi
	do_new "$2" "$3"
elif [ "$1" = "umount" ] ; then
	if ! [ $# = 3 ] ; then
		echo umount requires 2 more args 
		exit 1
	fi
	do_umount "$2" "$3"
elif [ "$1" = "send" ] ; then
	if ! [ $# = 5 ] ; then
		echo send requires 4 more args 
		exit 1
	fi
	do_send "$2" "$3" "$4" "$5"
else
	echo bad cmd
	exit 1
fi