#!/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
from winswitch.util.process_util import SimpleLineProcess

DEBUG_ARD = "--debug-ARD" in sys.argv
ARD_TIMEOUT=45

ARD_in_use = False
def is_ARD_in_use():
	global ARD_in_use
	return	ARD_in_use

class ARDControl(SimpleLineProcess):

	def __init__(self, kickstart_args, password=None, start_callback=None, exit_callback=None, log_full_command=True):
		args = ["sudo", "-S", "/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart"]
		args += kickstart_args
		self.password = password
		SimpleLineProcess.__init__(self, args, None, None, None, start_callback, exit_callback, False)
		self.usePTY = False
		self.env = self.make_env()
		self.DEBUG = True
		self.LOG_ALL_DATA = False

	def dataReceived(self, data):
		SimpleLineProcess.dataReceived(self, data)
		self.sdebug("buffer=%s" % self.buffer, data)
		if self.buffer=="Password:":
			self.slog("sending sudo password", data)
			self.write("%s\n" % self.password)
			self.buffer=''

	def handle(self, line):
		self.sdebug(None, line)

	def start(self):
		""" Set the lock flag and start the process """
		global ARD_in_use
		if ARD_in_use:
			self.serror("WARNING: ARD_in_use!")
		else:
			ARD_in_use = True
		SimpleLineProcess.start(self)
		def check_terminated():
			self.slog("process=%s, terminated=%s" % (self.process, self.terminated))
			if not self.terminated and self.process:
				global ARD_in_use
				ARD_in_use = False
				self.process.loseConnection()
		self.callLater(ARD_TIMEOUT, check_terminated)

	def exit(self):
		""" Free the lock """
		global ARD_in_use
		ARD_in_use = False
		SimpleLineProcess.exit(self)


def stop_ARD(password):
	proc = ARDControl(["-deactivate", "-configure", "-access", "-off"], password=password, log_full_command=True)
	proc.start()

def start_ARD(password, vnc_password, done_cb):
	proc = ARDControl(["-activate", "-configure", "-access", "-on",
						"-clientopts", "-setvnclegacy", "-vnclegacy", "yes",
						"-clientopts", "-setvncpw", "-vncpw", vnc_password,
						"-restart", "-agent", "-privs", "-all"],
						password=password, exit_callback=done_cb, log_full_command=DEBUG_ARD)
	proc.start()
