#!/usr/bin/env python

import sys
import subprocess

"""
This script is used to tell the client when the command has terminated.
This is necessary for win32/Xming clients where the tunnel plink/putty/openssh does not exit.
We send a CLOSE message to the local server, this is forwarded to the client which can then terminate the tunnel cleanly.
"""
#from winswitch.util.simple_logger import Logger
#Logger(self, log_colour=Logger.HIGHLIGHTED_BROWN)
def do_notify_client(clientID, sessionID):
	from winswitch.util.file_io import get_local_server_socket
	from winswitch.net.commands import CLOSE_SESSION
	from winswitch.util.format_util import format_message
	from winswitch.net.unix_socket_util import unix_socket_send

	message = "%s\n" % format_message(CLOSE_SESSION, [clientID, sessionID])
	path = get_local_server_socket()
	unix_socket_send(path, message)

def notify_client(clientID, sessionID):
	try:
		do_notify_client(clientID, sessionID)
	except:
		import traceback
		traceback.print_exc()
		print("error notifying client..")

def usage():
	print("Usage: %s clientID sessionID command [arguments ...]")
	print("")
	print("  clientID         The owner of the session")
	print("  sessionID        The session identification")
	print("  command          The command to start")
	print("  arguments        Optional arguments for the command")
	print("")
	print("Starts the given command and notifies the Window Switch")
	print("server when it terminates.")
	print("This is not meant to be used directly.")
	print("It is used by Microsoft Windows clients to ensure that")
	print("tunnels are closed once the command terminates.")


def main():
	if len(sys.argv)<3:
		print("invalid number of arguments")
		usage()
		return	1
	clientID = sys.argv[1]
	sessionID = sys.argv[2]
	cmd = sys.argv[3:]
	print("starting %s" % (" ".join(cmd)))
	proc = subprocess.Popen(cmd)
	proc.wait()
	notify_client(clientID, sessionID)
	return proc.returncode

if __name__ == "__main__":
	sys.exit(main())
