#!/usr/bin/python
#
# Copyright (c) Citrix Systems 2007-2011
# Author: Gianni Tedesco and Dave Scott
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; version 2.1 only. with the special
# exception on linking described in file 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 Lesser General Public License for more details.

import subprocess

path = "/sbin:/usr/sbin:/bin:/usr/bin"

xenstore_write_cmd = "xenstore-write"

def doexec(args):
	"""Execute a subprocess, then return its return code, stdout and stderr"""
	proc = subprocess.Popen([ "/usr/bin/env", "PATH=%s" % path ] + args,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)
	rc = proc.wait()
	stdout = proc.stdout
	stderr = proc.stderr
	return (rc, stdout, stderr)

def xenstore_write(path, value):
	(rc, stdout, stderr) = doexec([xenstore_write_cmd, path, value])

def enable_core_dumps():
	from resource import getrlimit, RLIMIT_CORE, setrlimit

	limit = 64 * 1024 * 1024
	oldlimits = getrlimit(RLIMIT_CORE)
	hardlimit = oldlimits[1]
	if limit > hardlimit:
		hardlimit = limit
	setrlimit(RLIMIT_CORE, (limit, hardlimit))
	return limit

def main(argv):
	import os

	qemu_env = os.environ
	qemu_dm_list =[]
	loc1 = '/usr/lib/xen/bin/qemu-dm'
	loc2 = '/usr/lib64/xen/bin/qemu-dm'
	loc3 = '/usr/lib/xen-4.1/bin/qemu-dm'
	loc4 = '/usr/lib/xen-4.2/bin/qemu-dm'
	loc5 = '/usr/lib/xen-4.4/bin/qemu-dm'
	qemu_dm_list = [loc1,loc2,loc3,loc4,loc5]
	qemu_dm = None
	for loc in qemu_dm_list:
		if os.path.exists(loc):
			qemu_dm = loc
	if qemu_dm is None:
		raise Exception("Cannot find qemu-dm in %s" % qemu_dm_list)

	domid = int(argv[1])
	qemu_args = ['qemu-dm-%d'%domid] + argv[2:]

	# Workaround http://unix.stackexchange.com/questions/39495/domain-ubuntu-hvm-does-not-exists-xen-ubuntu-hvm-guest-os-installation-pro
	if os.path.exists("/usr/share/qemu-linaro/qemu"):
		qemu_args = qemu_args + [ "-L", "/usr/share/qemu-linaro/qemu" ]

	print "qemu-dm-wrapper in python:"
	print "Using domid: %d" % domid
	print "Arguments: %s" % " ".join(argv[1:])
	print "everything else is from qemu-dm:"

	core_dump_limit = enable_core_dumps()
	print "core dump limit: %d" % core_dump_limit

	xenstore_write("/local/domain/%d/qemu-pid" % domid, "%d" % os.getpid())

	os.dup2(1, 2)
	os.execve(qemu_dm, qemu_args, qemu_env)

if __name__ == '__main__':
	from sys import argv
	raise SystemExit, main(argv)
