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

from winswitch.util.simple_logger import Logger, set_loggers_debug, set_log_to_tty
logger = Logger("server_cmd")
set_loggers_debug(False)
set_log_to_tty(False)
from winswitch.server.server_monitor import ServerMonitor, set_show_info_cb


class ServerCLI(ServerMonitor):
	def __init__(self, cmd, option):
		set_show_info_cb(self.handle_command)
		self.cmd = cmd
		self.option = option
		ServerMonitor.__init__(self, -1)

	def __str__(self):
		return	"ServerCLI"

	def handle_command(self, server):
		if self.cmd=="list":
			if self.option=="users":
				users = server.get_active_users()
				print("#found %s users:" % len(users))
				for user in users:
					print("%s: %s" % (user.uuid, user.name))
			elif self.option=="sessions":
				sessions = server.get_live_sessions(allow_shadow=False, ignore=[])
				print("#found %s sessions:" % len(sessions))
				for session in sessions:
					print("%s: %s" % (session.ID, session.name))
			elif self.option=="commands":
				commands = server.server_commands
				print("#found %s commands:" % len(commands))
				for command in commands:
					print("%s: %s" % (command.uuid, command.name))
			else:
				print("unknown option for command %s: %s" % (self.cmd, self.option))
		else:
			print("unknown command: %s" % self.cmd)
		self.stop()

def show_help():
	cmd = os.path.basename(sys.argv[0])
	print("usage:")
	print("%s list users" % cmd)
	print("%s list sessions" % cmd)
	print("%s list commands" % cmd)

def main():
	if len(sys.argv)!=3:
		return show_help()

	cmd = sys.argv[1]
	if cmd not in ["list"]:
		return show_help()
	option = sys.argv[2]
	try:
		server_cmd = ServerCLI(cmd, option)
		server_cmd.start()
	except Exception, e:
		print("server_monitor.main() exception: %s" % e)
		traceback.print_exc(file=sys.stdout)
		sys.exit(1)
		if server_cmd:
			server_cmd.stop()


if __name__ == "__main__":
	main()
