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

BIN_PATHS = []
if sys.platform.startswith("darwin"):
	BIN_PATHS.append("/usr/X11/bin/")
	BIN_PATHS.append("/opt/local/bin/")

def which(*names):
	return which_extra([], *names)

def which_extra(extra_bin_paths=[], *names):
	for name in names:
		cmd = ["which", name]
		try:
			proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
			out, _ = proc.communicate()
			if proc.returncode!=0 or not out:
				continue
			c = out.replace("\n", "").replace("\r", "")
			if os.path.exists(c):
				return	c
		except:
			continue
	for bin_path in BIN_PATHS+extra_bin_paths:
		for name in names:
			cmd_path = os.path.join(bin_path, name)
			if os.path.exists(cmd_path):
				return	cmd_path
	return	"/usr/bin/%s" % names[0]

def win32_which(*names):
	#which for win32:
	#see http://nedbatchelder.com/code/utilities/wh.py
	for cmd in names:
		paths = os.environ["PATH"].split(";")
		if "iexplore" in names and "ProgramFiles" in os.environ:
			ie_dir = os.path.join(os.environ["ProgramFiles"], "Internet Explorer")
			paths.append(ie_dir)
		for path in paths:
			if "." in cmd:
				pathext = ['']
			else:
				pathext = os.environ["PATHEXT"].split(";")
			for ext in pathext:
				filePath = os.path.join(path, cmd + ext)
				if os.path.exists(filePath):
					return	os.path.normcase(filePath)
	return	None
