#!/usr/bin/python
#
#    testdrive-kvm - run a cd or an image in kvm
#    Copyright (C) 2010 Canonical Ltd.
#    Copyright (C) 2010 Dustin Kirkland
#
#    Authors: Dustin Kirkland <kirkland@canonical.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, version 3 of the License.
#
#    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, see <http://www.gnu.org/licenses/>.

PKG = "testdrive"
PKGRC = "%src" % PKG

import commands, os, sys

# Intialize vars from environment
HOME = os.getenv("HOME", "")
MEM = os.getenv("MEM", "")
CDROM = os.getenv("CDROM", "")
DISK = os.getenv("DISK", "")
KVM_ARGS = os.getenv("KVM_ARGS", "")

def error(str):
	print("\nERROR: %s\n" % str)
	sys.exit(1)

# Ensure that KVM exists
(status, output) = commands.getstatusoutput("which kvm")
if status != 0:
	error("KVM is not installed")

# Source config files
config_files = ["/etc/%s" % PKGRC, "%s/.%s" % (HOME, PKGRC), "%s/.config/%s/%s" % (HOME, PKG, PKGRC) ]
for i in config_files:
	if os.path.exists(i):
		try:
			execfile(i)
		except:
			error("Invalid configuration [%s]" % i)

# Pull CDROM or DISK from the command line arguments
i = 1
while i < len(sys.argv):
	print(os.sys.argv[i])
	(status, output) = commands.getstatusoutput("file %s | grep -qs 'ISO 9660 CD-ROM'" % os.sys.argv[i])
	if status == 0:
		CDROM = "-cdrom %s" % os.sys.argv[i]
	(status, output) = commands.getstatusoutput("file %s | grep -qs 'Qemu Image'" % os.sys.argv[i])
	if status == 0:
		DISK = "-drive file=%s,if=virtio,index=0,boot=on" % os.sys.argv[1]
	i += 1

# Ensure that at least a CDROM or a DISK is specified
if len(CDROM) == 0 and len(DISK) ==0:
	error("You must provide a path to either an ISO or a disk image")

print("kvm -m %s %s %s %s" % (MEM, CDROM, DISK, KVM_ARGS))
os.system("kvm -m %s %s %s %s" % (MEM, CDROM, DISK, KVM_ARGS))
