#!/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, sys, inspect

WIN32 = sys.platform.startswith("win")
OSX = sys.platform.startswith("darwin")

from winswitch.util.simple_logger import Logger
logger=Logger("paths", log_colour=Logger.CYAN)
DEBUG_PATHS = "--debug-paths" in sys.argv
def debug_paths(msg):
	if DEBUG_PATHS:
		logger.slog(None, msg)


def valid_dir(path):
	try:
		return path and os.path.exists(path) and os.path.isdir(path)
	except:
		return False

def get_argv_path(name):
	arg = "--%s=" % name
	for test in sys.argv:
		if test.startswith(arg):
			path = test[len(arg):]
			#print("found path override for %s from %s: %s" % (name, test, path))
			return	path
	env_name = name.replace("-", "_")
	if env_name in os.environ:
		return	os.environ[env_name]
	return	None

#This one requires some code (ugly too)... but we need it early (ie for logging), so keep it here
APP_DIR = get_argv_path("app_dir")
SHARE_DIR = get_argv_path("share_dir")
ETC_DIR = get_argv_path("etc_dir")
LIBEXEC_DIR = get_argv_path("libexec_dir")
WINSWITCH_LIBEXEC_DIR = get_argv_path("winswitch_libexec_dir")
WINSWITCH_SHARE_DIR = get_argv_path("winswitch_share_dir")
if not APP_DIR:
	frozen = getattr(sys, 'frozen', '')
	if frozen in ('dll', 'console_exe', 'windows_exe'):
		# py2exe:
		APP_DIR = os.path.dirname(sys.executable)
		if not SHARE_DIR:
			SHARE_DIR = APP_DIR
		if not WINSWITCH_SHARE_DIR:
			WINSWITCH_SHARE_DIR = SHARE_DIR
		debug_paths("found Windows frozen app, using APP_DIR=%s" % APP_DIR)
	elif OSX:		#or frozen in ('macosx_app',)
		rsc = None
		try:
			import gtkosx_application		#@UnresolvedImport
			rsc = gtkosx_application.gtkosx_application_get_resource_path()
		except:
			pass
		# py2app:
		if not valid_dir(rsc):
			if 'RESOURCEPATH' in os.environ.keys():
				rsc = os.environ['RESOURCEPATH']
				debug_paths("MacOSX: RESOURCEPATH=%s" % rsc)
			else:
				rsc = os.getcwd()
				debug_paths("MacOSX: cwd=%s" % rsc)
			if rsc=="/":
				rsc = __file__
				debug_paths("MacOSX: __file__=%s" % rsc)
		#print("paths: rsc=%s" % rsc)
		if rsc:
			CONTENTS = "/Contents/"
			i = rsc.rfind(CONTENTS)
			if i>0:
				APP_DIR = rsc[:i+len(CONTENTS)]
				if not valid_dir(SHARE_DIR):
					SHARE_DIR = os.path.join(APP_DIR, "Resources", "share")
				if not valid_dir(ETC_DIR):
					ETC_DIR = os.path.join(APP_DIR, "Resources", "etc")
				if not valid_dir(WINSWITCH_LIBEXEC_DIR):
					WINSWITCH_LIBEXEC_DIR = os.path.join(APP_DIR, "Resources", "libexec", "winswitch")

		debug_paths("MacOSX: rsc=%s, APP_DIR=%s, SHARE_DIR=%s" % (rsc,APP_DIR,SHARE_DIR))
	if not valid_dir(APP_DIR):
		APP_DIR = os.path.dirname(inspect.getfile(sys._getframe(1)))
	if not valid_dir(APP_DIR):
		APP_DIR = os.path.dirname(sys.argv[0])
	if not valid_dir(APP_DIR):
		APP_DIR = os.getcwd()
debug_paths("final APP_DIR=%s" % APP_DIR)

PREFIX_DIR = "/usr"
ETC_SEARCH_ORDER = ["/etc", "/usr/local/etc"]
PREFIX_SEARCH_ORDER = ["/usr", "/usr/local"]
BIN_SEARCH_ORDER = ["/usr/bin", "/usr/local/bin"]
if APP_DIR.startswith("/usr/local/"):
	PREFIX_DIR = "/usr/local"
	PREFIX_SEARCH_ORDER.reverse()
	ETC_SEARCH_ORDER.reverse()
	BIN_SEARCH_ORDER.reverse()


if not valid_dir(SHARE_DIR):
	paths = []
	if not WIN32:
		paths.append("%s/share" % APP_DIR)
		for d in PREFIX_SEARCH_ORDER:
			paths.append("%s/share" % d)
	elif APP_DIR:
		paths.append(os.path.join(APP_DIR, "share"))
	for path in paths:
		if valid_dir(path):
			SHARE_DIR = path
			debug_paths("found SHARE_DIR=%s" % SHARE_DIR)
			break
if not valid_dir(WINSWITCH_SHARE_DIR):
	WINSWITCH_SHARE_DIR = os.path.join(SHARE_DIR, "winswitch")

if not valid_dir(WINSWITCH_SHARE_DIR):
	raise Exception("Cannot continue without being able to locate the share directory!\n"
				"Either specify --app_dir=/path/to/winswitch or --winswitch_share_dir=/path/to/winswitch/share\n"
				"You can also specify 'app_dir' and 'winswitch_share_dir' using environment variables\n"
				"If you have used an installer, re-installing may fix this problem.")
else:
	debug_paths("final WINSWITCH_SHARE_DIR=%s" % WINSWITCH_SHARE_DIR)


def find_prefixed_subdir(dirname):
	return	find_prefixed_subdir_from(dirname, PREFIX_SEARCH_ORDER)

def find_prefixed_subdir_from(dirname, dirs):
	return	find_valid_dir([(os.path.join(x,dirname)) for x in dirs])

def find_valid_dir(dirs):
	for d in dirs:
		if valid_dir(d):
			return	d
	return	None

if not valid_dir(ETC_DIR):
	ETC_DIR = find_prefixed_subdir_from("etc", ETC_SEARCH_ORDER)
if not valid_dir(LIBEXEC_DIR):
	LIBEXEC_DIR = find_prefixed_subdir("libexec")
	if not valid_dir(LIBEXEC_DIR):
		""" debian/ubuntu don't have libexec... """
		LIBEXEC_DIR = find_prefixed_subdir("lib")
if not LIBEXEC_DIR:
	#we need a valid string in there
	LIBEXEC_DIR = os.path.join("usr", "lib")
if not valid_dir(WINSWITCH_LIBEXEC_DIR):
	WINSWITCH_LIBEXEC_DIR = find_prefixed_subdir("libexec/winswitch")
	if not valid_dir(WINSWITCH_LIBEXEC_DIR):
		WINSWITCH_LIBEXEC_DIR = find_prefixed_subdir("lib/winswitch")
		if not valid_dir(WINSWITCH_LIBEXEC_DIR):
			# we failed to locate it, but at least set it to something (even if it does not exist)
			WINSWITCH_LIBEXEC_DIR = os.path.join(LIBEXEC_DIR, "winswitch")
debug_paths("final ETC_DIR=%s, WINSWITCH_LIBEXEC_DIR=%s, LIBEXEC_DIR=%s" % (ETC_DIR, WINSWITCH_LIBEXEC_DIR, LIBEXEC_DIR))

GNOME_SETTINGS_DAEMON=None
if not WIN32:
	dirs = [LIBEXEC_DIR]+PREFIX_SEARCH_ORDER+[("%s/bin" % x) for x in PREFIX_SEARCH_ORDER]
	for d in dirs:
		if d:
			filename = os.path.join(d, "gnome-settings-daemon")
			if os.path.exists(filename):
				GNOME_SETTINGS_DAEMON = filename
				break

ICON_DIR = os.path.join(WINSWITCH_SHARE_DIR, "icons")
if not os.path.exists(ICON_DIR) or not os.path.isdir(ICON_DIR):
	#tried our best...
	msg = "Don't know how to locate icons! __file__=%s, WINSWITCH_SHARE_DIR=%s, we tried: %s" % (__file__, WINSWITCH_SHARE_DIR, ICON_DIR)
	logger.serror(msg)
	raise Exception(msg)
ANIM_DIR = os.path.join(WINSWITCH_SHARE_DIR, "anim")

# File locations
if WIN32:
	WINSWITCH_DIR = "Window-Switch"
	XPRA_DIR="xpra"
	PUTTY_DIR = os.path.join(APP_DIR, "PuTTY")
else:
	WINSWITCH_DIR = ".winswitch"
	XPRA_DIR=".xpra"
	PUTTY_DIR=None
tmp=get_argv_path("winswitch_conf_dir")
if tmp:
	WINSWITCH_DIR = tmp

TEMP_DIR = "tmp"
SERVER_CONFIG_EXTENSION=".wsw"

CLIENT_DIR = "client"
# in client/ :
CLIENT_CONF = "client.conf"
AVATAR_ICON_FILE = "avatar.ico"
AUTHORIZED_KEYS_FILE = "authorized_keys"
SERVERS_DIR = "servers"
EXPORTS_DIR = "exports"
SESSION_TEMP_DIR = "session-temp"
COMMAND_ICONS_DIR = "command-icons"
LIBVIRT_DIR = ".libvirt"
SYSTEM_LIBVIRT_DIR = "/var/lib/libvirt"

GLOBAL_SERVER_DIR = "%s/winswitch" % ETC_SEARCH_ORDER[0]
GLOBAL_SERVER_STATE_DIR = "/var/lib/winswitch"
GLOBAL_SERVER_LOG_DIR = "/var/log"
SERVER_LOG = "server-%Y%m%d-%H%M%S.log"
CLIENT_LOG = "client-%Y%m%d-%H%M%S.log"
APPLET_LOG = "applet-%Y%m%d-%H%M%S.log"
SERVER_DIR = "server"
# in server/ :
SERVER_CONF = "server.conf"
PORTS_CONF = "ports.conf"
PORT_FILENAME="server_port"
SESSION_DIR="sessions"
MENU_DIR="menu"
ACTIONS_DIR="actions"
XSESSIONS_DIR="xsessions"
PROTOCOLS_DIR="protocols"
LOCK_DIR="lock"
XMODMAP_DIR="xmodmap"

SESSION_CONFIG_FILENAME = "config"
SESSION_CONFIG_EXT = ".txt"

#local socket
LOCAL_SOCKET_NAME="socket"
#server socket
SERVER_SOCKET_NAME="socket"

# Our wrappers:
WINSWITCH_COMMAND_WRAPPER="winswitch_command_wrapper"
APP_DESKTOP_FILE="winswitch.desktop"

EXE = "Window-Switch.exe"
PIPE_EXE = "Window-Switch-Pipe.exe"

XSESSION_DIRS = [("%s/share/xsessions" % x) for x in PREFIX_SEARCH_ORDER]
HOST_PUBLIC_KEY_FILE = "ssh_host_rsa_key.pub"
# relative to share directory
DEVILSPIE_VNC_CONFIG = "devilspie/Xvnc.ds"
XORG_XDUMMY_XPRA_CONFIG = "xorg-xdummy-xpra.conf"
DESKTOP_BACKGROUND = "background.jpg"
WM_ICONS = "wm_icons"
DEFAULT_ICONS = "default_icons"
