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

VERBOSE_FLAG = "--winswitch-verbose"
WINSWITCH_ONLY_FLAG = "--winswitch-only"

verbose = VERBOSE_FLAG in sys.argv
if verbose:
	sys.argv.remove(VERBOSE_FLAG)
winswitch_only = WINSWITCH_ONLY_FLAG in sys.argv
if winswitch_only:
	sys.argv.remove(WINSWITCH_ONLY_FLAG)

from winswitch.util.simple_logger import set_log_to_tty
set_log_to_tty(verbose)

def usage():
	print("Usage: %s [--winswitch-verbose] command [arguments ...]" % sys.argv[0])
	print("")
	print("  command                  The command to start")
	print("  arguments                Optional arguments for the command")
	print("  -h  --help               This information")
	print("  --winswitch-verbose      Turn on verbose logging")
	print("  --winswitch-only         Do not start commands outside Window Switch")
	print("")
	print("This is a wrapper script for launching commands")
	print("via Window Switch.")
	print("If the Window Switch client is running ('winswitch_applet'),")
	print("it will be used to start the command line specified,")
	print("which will make it network transparent.")
	print("")
	print("If the client is not available, or if it declines to start the")
	print("command line given (keyboard modifiers can be used to toggle this behaviour)")
	print("the command line (command and optional arguments) will be used directly.")
	print("")
	print("For example:")
	print(" %s xterm" % sys.argv[0])
	print("Will start an xterm, either directly or via Window Switch,")
	print("depending on the client configuration and availability.")
	print("")
	print("You can use this wrapper to modify your desktop shortcuts,")
	print("the commands will still function, even when Window Switch is not running.")

""" show usage if no arguments, or if single argument is an obvious ask for help """
if len(sys.argv)==1 or (len(sys.argv)==2 and (sys.argv[1]=="-h" or sys.argv[1]=="--help")):
	usage()
	sys.exit(0)

# Our imports
from winswitch.net.local_socket_client import LocalSocketClient
from winswitch.net.local_common import COMMAND_WRAPPER_START_SESSION
from winswitch.util.format_util import format_message


def start_via_client(argv):
	try:
		lsc = LocalSocketClient()
		if not lsc.test_socket_exists():
			print("%s: socket not found - is the client running?" % sys.argv[0])
			return	False
		msg = format_message(COMMAND_WRAPPER_START_SESSION, params=argv)
		e = lsc.send([msg])
		if e!=0:
			print("%s: failed to send via socket" % sys.argv[0])
		return	e==0
	except Exception, e:
		print("%s: error sending to client: %s" % (sys.argv[0], e))
		return	False
		

def execute_command(argv):
	if start_via_client(argv):
		return	0
	elif winswitch_only:
		print("failed to start inside Window Switch")
		print("Giving up as requested")
		return 1

	#socket failed to send, so start the command directly
	os.execvp(argv[0], argv)

def main():
	exit_code = 1
	if len(sys.argv)>1:
		exit_code = execute_command(sys.argv[1:])
	if exit_code:
		sys.exit(exit_code)

if __name__ == '__main__':
	main()
