#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3

import sys
import os

from winswitch.util.simple_logger import Logger, set_log_to_file, set_log_to_tty
logfile = None
LOG_FILE_ARG = "--log-file"
lx = None
for x in sys.argv:
	if lx and lx==LOG_FILE_ARG:
		logfile = x
	lx = x
print_pid = "--print-pid" in sys.argv
daemon = "--daemon" in sys.argv
QUIET = "--quiet" in sys.argv
if QUIET:
	set_log_to_file(False)
	set_log_to_tty(False)

from winswitch.util.common import csv_list
from winswitch.util.daemonize import daemonize
from winswitch.util.paths import WINSWITCH_LIBEXEC_DIR
from winswitch.util.process_util import get_output
logger = Logger("virt_server_daemonizer")


def start_daemon(logfile, args, cwd=None, env=None, use_daemon_wrapper=True):
	if use_daemon_wrapper:
		script_cmd = os.path.join(WINSWITCH_LIBEXEC_DIR, "virt_server_daemonizer")
		args_list = [script_cmd, "--quiet",
				"--print-pid", "--daemon", "--log-file", logfile,
				"--"]
		args_list += args
	else:
		args_list = args
	return	grab_daemon_pid(args_list, cwd, env)

def grab_daemon_pid(args_list, cwd=None, env=None):
	stdoutdata, stderrdata = None, None
	try:
		code, stdoutdata, stderrdata = get_output(args_list, cwd=cwd, env=env)
		if stdoutdata and code==0:
			pid = int(stdoutdata)
			logger.slog("returncode=%s, stdoutdata=%s, stderrdata=%s, pid=%s" % (code, stdoutdata, stderrdata, pid), args_list, cwd, env)
			return pid
	except Exception, e:
		logger.serr("args_list=%s, stdout=%s, stderr=%s" % (csv_list(args_list), stdoutdata, stderrdata), e, args_list, cwd, env)
	return None



def may_daemonize():
	if daemon:
		daemonize(print_pid, logfile)

def main():
	logger.slog("sys.argv=%s" % csv_list(sys.argv))
	assert len(sys.argv)>=2
	may_daemonize()
	index = 0
	args = []
	for x in sys.argv:
		if x=="--":
			args = sys.argv[index+1:]
			break
		index += 1
	assert len(args)>0
	cmd = args[0]
	logger.slog("cmd=%s, args=%s, env=%s" % (cmd, csv_list(args), os.environ))
	os.execvpe(cmd, args, os.environ)

if __name__ == "__main__":
	main()
