#!/usr/bin/python2
# Copyright (C) 2010, Thomas Leonard
# See the README file for details, or visit http://0install.net.

from __future__ import print_function

import locale
import logging
from logging import warn
try:
	locale.setlocale(locale.LC_ALL, '')
except locale.Error:
	warn('Error setting locale (eg. Invalid locale)')

import os, sys

## PATH ##

from optparse import OptionParser

from zeroinstall.injector import reader, model
from zeroinstall.injector.config import load_config
from zeroinstall import support, alias, helpers, _
from zeroinstall.support import basedir

config = load_config()

def export(name, value):
	"""Try to guess the command to set an environment variable."""
	shell = os.environ.get('SHELL', '?')
	if 'csh' in shell:
		return "setenv %s %s" % (name, value)
	return "export %s=%s" % (name, value)

def find_path(paths):
	"""Find the first writable path in the list,
	skipping /bin, /sbin and everything under /usr except /usr/local/bin"""
	for path in paths:
		if path.startswith('/usr/') and not path.startswith('/usr/local/bin'):
			# (/usr/local/bin is OK if we're running as root)
			pass
		elif path.startswith('/bin') or path.startswith('/sbin'):
			pass
		elif os.path.realpath(path).startswith(basedir.xdg_cache_home):
			pass # print "Skipping cache", first_path
		elif not os.access(path, os.W_OK):
			pass # print "No access", first_path
		else:
			break
	else:
		return None

	return path

# Do this here so we can include it in the help message.
# But, don't abort if there isn't one because we might
# be doing something else (e.g. --manpage)
first_path = find_path(os.environ['PATH'].split(':'))
in_path = first_path is not None
if not in_path:
	first_path = os.path.expanduser('~/bin/')

parser = OptionParser(usage="usage: %%prog [options] alias [interface [main]]\n\n"
		"Creates a script to run 'interface' (will be created in\n"
		"%s unless overridden by --dir).\n\n"
		"If no interface is given, edits the policy for an existing alias.\n"
		"For interfaces providing more than one executable, the desired\n"
		"'main' binary or command may also be given." % first_path)
parser.add_option("-c", "--command", help="the command the alias will run (default 'run')", metavar='COMMNAD')
parser.add_option("-m", "--manpage", help="show the manual page for an existing alias", action='store_true')
parser.add_option("-r", "--resolve", help="show the URI for an alias", action='store_true')
parser.add_option("-v", "--verbose", help="more verbose output", action='count')
parser.add_option("-V", "--version", help="display version information", action='store_true')
parser.add_option("-d", "--dir", help="install in DIR", dest="user_path", metavar="DIR")

(options, args) = parser.parse_args()

if options.verbose:
	logger = logging.getLogger()
	if options.verbose == 1:
		logger.setLevel(logging.INFO)
	else:
		logger.setLevel(logging.DEBUG)
	hdlr = logging.StreamHandler()
	fmt = logging.Formatter("%(levelname)s:%(message)s")
	hdlr.setFormatter(fmt)
	logger.addHandler(hdlr)

if options.version:
	import zeroinstall
	print("0alias (zero-install) " + zeroinstall.version)
	print("Copyright (C) 2010 Thomas Leonard")
	print("This program comes with ABSOLUTELY NO WARRANTY,")
	print("to the extent permitted by law.")
	print("You may redistribute copies of this program")
	print("under the terms of the GNU Lesser General Public License.")
	print("For more information about these matters, see the file named COPYING.")
	sys.exit(0)

if options.manpage:
	if len(args) != 1:
		os.execlp('man', 'man', *args)
		sys.exit(1)

if len(args) < 1 or len(args) > 3:
	parser.print_help()
	sys.exit(1)
alias_prog, interface_uri, main = (list(args) + [None, None])[:3]
command = options.command

if options.resolve or options.manpage:
	if interface_uri is not None:
		parser.print_help()
		sys.exit(1)

if options.user_path:
	first_path = options.user_path

if interface_uri is None:
	if options.command:
		print("Can't use --command when editing an existing alias", file=sys.stderr)
		sys.exit(1)
	try:
		if not os.path.isabs(alias_prog):
			full_path = support.find_in_path(alias_prog)
			if not full_path:
				raise alias.NotAnAliasScript("Not found in $PATH: " + alias_prog)
		else:
			full_path = alias_prog

		alias_info = alias.parse_script(full_path)
		interface_uri = alias_info.uri
		main = alias_info.main
		command = alias_info.command
	except (alias.NotAnAliasScript, IOError) as ex:
		# (we get IOError if e.g. the script isn't readable)
		if options.manpage:
			logging.debug("not a 0alias script '%s': %s", alias_prog, ex)
			os.execlp('man', 'man', *args)
		print(str(ex), file=sys.stderr)
		sys.exit(1)

interface_uri = model.canonical_iface_uri(interface_uri)

if options.resolve:
	print(interface_uri)
	sys.exit(0)

if options.manpage:
	sels = helpers.ensure_cached(interface_uri, command = command or 'run')
	if not sels:
		# Cancelled by user
		sys.exit(1)

	if sels.commands:
		selected_command = sels.commands[0]
	else:
		print("No <command> in selections!", file=sys.stderr)
	selected_impl = sels.selections[interface_uri]

	impl_path = selected_impl.local_path or config.iface_cache.stores.lookup_any(selected_impl.digests)

	if main is None:
		main = selected_command.path
		if main is None:
			print("No main program for interface '%s'" % interface_uri, file=sys.stderr)
			sys.exit(1)

	prog_name = os.path.basename(main)
	alias_name = os.path.basename(args[0])

	assert impl_path

	# TODO: the feed should say where the man-pages are, but for now we'll accept
	# a directory called man in some common locations...
	for mandir in ['man', 'share/man', 'usr/man', 'usr/share/man']:
		manpath = os.path.join(impl_path, mandir)
		if os.path.isdir(manpath):
			# Note: unlike "man -M", this also copes with LANG settings...
			os.environ['MANPATH'] = manpath
			os.execlp('man', 'man', prog_name)
			sys.exit(1)

	# No man directory given or found, so try searching for man files

	manpages = []
	for root, dirs, files in os.walk(impl_path):
		for f in files:
			if f.endswith('.gz'):
				manpage_file = f[:-3]
			else:
				manpage_file = f
			if manpage_file.endswith('.1') or \
			   manpage_file.endswith('.6') or \
			   manpage_file.endswith('.8'):
			   	manpage_prog = manpage_file[:-2]
				if manpage_prog == prog_name or manpage_prog == alias_name:
					os.execlp('man', 'man', os.path.join(root, f))
					sys.exit(1)
				else:
					manpages.append((root, f))

	print("No matching manpage was found for '%s' (%s)" % (alias_name, interface_uri))
	if manpages:
		print("These non-matching man-pages were found, however:")
		for root, file in manpages:
			print(os.path.join(root, file))
	sys.exit(1)

if not os.path.isdir(first_path):
	print("(creating directory %s)" % first_path)
	os.makedirs(first_path)

if len(args) == 1:
	os.execlp('0launch', '0launch', '-gd', '--', interface_uri)
	sys.exit(1)

try:
	if not options.user_path:
		if alias_prog == '0launch':
			raise model.SafeException(_('Refusing to create an alias named "0launch" (to avoid an infinite loop)'))

	interface = model.Interface(interface_uri)
	if not reader.update_from_cache(interface):
		print("Interface '%s' not currently in cache. Fetching..." % interface_uri, file=sys.stderr)
		if os.spawnlp(os.P_WAIT, '0launch', '0launch', '-d', interface_uri):
			raise model.SafeException("0launch failed")
		if not reader.update_from_cache(interface):
			raise model.SafeException("Interface still not in cache. Aborting.")

	script = os.path.join(first_path, alias_prog)
	if os.path.exists(script):
		raise model.SafeException("File '%s' already exists. Delete it first." % script)
		sys.exit(1)
except model.SafeException as ex:
	print(ex, file=sys.stderr)
	sys.exit(1)

seen = set([interface_uri])
while True:
	feed = config.iface_cache.get_feed(interface_uri)
	replacement_uri = feed.get_replaced_by()
	if replacement_uri is None:
		break
	print(_("(interface {old} has been replaced by {new}; using that instead)").format(old = interface_uri, new = replacement_uri))
	assert replacement_uri not in seen, "loop detected!"
	seen.add(replacement_uri)
	interface_uri = replacement_uri

wrapper = open(script, 'w')
alias.write_script(wrapper, interface_uri, main, command = command)

# Make new script executable
os.chmod(script, 0o111 | os.fstat(wrapper.fileno()).st_mode)
wrapper.close()

#print "Created script '%s'." % script
#print "To edit policy: 0alias %s" % alias_prog
if options.user_path:
	pass		# Assume user knows what they're doing
elif not in_path:
	print('Warning: %s is not in $PATH. Add it with:\n%s' % (first_path, export('PATH', first_path + ':$PATH')), file=sys.stderr)
else:
	shell = os.environ.get('SHELL', '?')
	if not (shell.endswith('/zsh') or shell.endswith('/bash')):
		print("(note: some shells require you to type 'rehash' now)")
