#!/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 traceback

def usage():
	print("Usage: %s [-d [-p]]" % sys.argv[0])
	print("")
	print("  -h   --help		Usage information")
	print("  -d   --daemon		Run as a daemon")
	print("  -p   --print-pid	Print pid (requires --daemon)")
	print("  --version			Print version information and exit")
	from winswitch.util.simple_logger import set_log_to_tty, set_log_to_file
	sys.argv.remove("--help")		#this causes gst to terminate our process! ouch, naughty
	set_log_to_file(False)
	set_log_to_tty(False)
	from winswitch.objects.common import add_argv_usage
	from winswitch.objects.server_settings import ServerSettings
	add_argv_usage(ServerSettings())
	print("")




def main():
	if "-h" in sys.argv or "--help" in sys.argv:
		usage()
		return
	if "--version" in sys.argv:
		from winswitch.util.version_info import print_version_info
		print_version_info()
		return
	#initialize logger
	from winswitch.util.simple_logger import set_log_filename, set_log_dir, set_log_to_file, set_log_to_tty, rotate_log_file
	set_log_to_file(False)
	set_log_to_tty(True)
	from winswitch.util.paths import SERVER_DIR, SERVER_LOG
	set_log_dir(SERVER_DIR)
	set_log_filename(SERVER_LOG)
	#detect flags
	daemon = "-d" in sys.argv or "--daemon" in sys.argv
	print_pid = "-p" in sys.argv or "--print-pid" in sys.argv
	if daemon:
		set_log_to_file(True)
		set_log_to_tty(False)
	from winswitch.server.controller import WinSwitchServer
	exit_code = 1
	server = WinSwitchServer()
	if server.check():
		if daemon and not sys.platform.startswith("win"):
			from winswitch.util.daemonize import daemonize
			daemonize(print_pid)
		elif print_pid:
			import os
			print("%s" % os.getpid())

		try :
			server.start()
			exit_code = 0
		except Exception, e:
			print("winswitch_server.py")
			print('*** Caught exception: %s: %s' % (type(e).__name__, e))
			traceback.print_exc()
			exit_code = 1
		server.cleanup()

	rotate_log_file()
	sys.exit(exit_code)

if __name__ == "__main__":
	main()
