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

#disable logging so all we get is the port:
from winswitch.util.simple_logger import Logger, set_log_to_file, set_log_to_tty, set_log_filename
from winswitch.globals import WIN32

logger=Logger("server_portinfo", log_colour=Logger.CYAN)

def	get_port_from_file(filename):
	if not os.path.exists(filename):
		return	(None, None)
	inp = open (filename, "r")
	host = None
	port = None
	for line in inp.readlines():
		pos = line.rfind(":")
		if pos>0:
			host = line[:pos]
			try:
				port = int(line[pos+1:])
			except:
				pass
	if not port:
		return	(None, None)
	return	 (host, port)

def get_local_servers_portinfo(connect_test=True):
	port_info = []
	as_root_list = [False]
	if not WIN32:
		as_root_list.insert(0, True)
	for as_root in as_root_list:
		pi = get_local_server_portinfo(as_root, connect_test)
		if pi:
			#(host, port, ID) = pi
			port_info.append(pi)
	logger.sdebug("=%s" % str(port_info), connect_test)
	return	port_info

def get_local_server_portinfo(as_root, connect_test=True, server_config=None):
	from winswitch.util.file_io import get_port_filename, get_local_server_config_filename, load_properties, is_valid_file
	port_filename = get_port_filename(as_root=as_root)
	ID = None
	if server_config:
		ID = server_config.ID
	else:
		conf_filename = get_local_server_config_filename(as_root=as_root)
		if not is_valid_file(conf_filename):
			logger.sdebug("config %s does not exist or is not valid" % conf_filename, as_root, connect_test, server_config)
			return	None
		server_props = load_properties(conf_filename)
		logger.sdebug("config(%s) loaded" % conf_filename, as_root, connect_test, server_config)
		if server_props:
			ID = server_props.get("ID")
			if ID:
				ID = ID.strip('"').strip("'")
	(host, port) = get_port_from_file(port_filename)
	logger.sdebug("ID=%s, port(%s)=%s" % (ID, port_filename, port))
	if not port or not ID:
		return	None
	if connect_test and not connect_ok(host, port):
		return	None
	return	(host, port, ID)

def connect_ok(host, port):
	ret = False
	sock = None
	try:
		if host=="0.0.0.0":
			host = "127.0.0.1"
		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		sock.settimeout(2)
		sock.connect((host, port))
		ret = True
		logger.sdebug("success: %s" % sock, host, port)
	except Exception, e:
		logger.sdebug("failed: %s" % e, host, port)
	if sock:
		sock.close()
	return	ret


def may_wait_and_exit(exit_code):
	if WIN32 and "--nowait" not in sys.argv:
		print("Press Enter to close")
		sys.stdin.readline()
	sys.exit(exit_code)

def main():
	set_log_filename("server_portinfo")
	set_log_to_file("--log-to-file" in sys.argv)
	set_log_to_tty("--debug-mode" in sys.argv)

	port_info = get_local_servers_portinfo()
	if len(port_info)>0:
		for (host, ip, ID) in port_info:
			print("%s:%d %s" % (host, ip, ID))
		may_wait_and_exit(0)
	else:
		may_wait_and_exit(1)

if __name__ == "__main__":
	main()
