#!/usr/bin/python
#
# LLRepo - LightLang repository manager
# Copyright (C) 2007-2016 Devaev Maxim
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
# apps/llrepo/src/llrepo.py.  Generated from llrepo.py.in by configure.


import sys
import os
import struct
import fcntl
import termios
import tempfile
import ftplib

sys.path.append("/usr/lib/llrepo")
import repos


#####
MyName = "llrepo"
Version = "2.2"

DeveloperMail = "mdevaev@gmail.com"

DictsResourcesType = "dicts"
SoundsResourcesType = "sounds"
AllResourcesTypes = [DictsResourcesType, SoundsResourcesType]

LocalRepositoriesType = "local"
RemoteRepositoriesType = "remote"
AllRepositoriesTypes = [LocalRepositoriesType, RemoteRepositoriesType]

DictsResourcesPostfix = ".bz2"
SoundsResourcesPostfix = ".tar.bz2"

SLSharesDir = "/usr/share/sl/"
DictsDir = SLSharesDir+DictsResourcesType+"/"
SoundsDir = SLSharesDir+SoundsResourcesType+"/"

###
CatProg = "/bin/cat"
TarProg = "/bin/tar"
BZip2Prog = "/usr/bin/bzip2"
SlProg = "/usr/bin/sl"

###
RemoteListCommand = "remotelist"
LocalListCommand = "locallist"
InstallCommand = "install"
RemoveCommand = "remove"
HelpCommand = "help"
VersionCommand = "version"
AllCommands = [RemoteListCommand, LocalListCommand,
	InstallCommand, RemoveCommand,
	HelpCommand, VersionCommand]


#####
def short_stdout(str, static = [""]) :
	sys.stdout.write(" "*len(static[0])+"\r"+str+"\r")
	sys.stdout.flush()
	static[0] = str

def get_terminal_width(fd = 1) :
	winsize_struct_packed = struct.pack("HHHH", 0, 0, 0, 0)
	try :
		winsize_struct_packed = fcntl.ioctl(fd, termios.TIOCGWINSZ, winsize_struct_packed)
	except : pass
	winsize_struct_unpacked = struct.unpack("HHHH", winsize_struct_packed)
	return ( winsize_struct_unpacked[1] if winsize_struct_unpacked[1] > 80 else 80 )

###
def sort_resources_list(resources_list, left = None, right = None) :
	if left == right == None :
		left = 0
		right = len(resources_list) - 1

	if left >= right :
		return

	i = j = left
	while j <= right :
		if resources_list[j]["resource_name"] <= resources_list[right]["resource_name"] :
			resources_list[i], resources_list[j] = resources_list[j], resources_list[i]
			i += 1
		j += 1

	sort_resources_list(resources_list, left, i - 2)
	sort_resources_list(resources_list, i, right)

###
def get_remote_resources_list(resources_type) :
	if not resources_type in AllResourcesTypes :
		return []

	###

	remote_resources_list = []

	for repos_item in repos.repos :
		print "Processing remote repository \"%s\"..." % (repos_item["server"])

		try :
			ftp = ftplib.FTP()
			print "--- server \"%s\" -> %s" % (repos_item["server"], ftp.connect(repos_item["server"], int(repos_item["port"])))
			print "--- server \"%s\" -> %s" % (repos_item["server"], ftp.login(repos_item["user"], repos_item["passwd"]))
			resources_files_list = ftp.nlst(os.path.join(repos_item["root"], resources_type))
		except Exception, err1 :
			try :
				print "--- server \"%s\" -> %s" % (repos_item["server"], ftp.quit())
			except Exception, err2 :
				print >> sys.stderr, "--- server \"%s\" :: warning, error while closing ftp: %s" % (repos_item["server"], str(err2))

			print >> sys.stderr, "Error while processing remote repository \"%s\": %s\n" % (repos_item["server"], str(err1))
			continue

		resources_count = 0

		for resources_files_list_item in resources_files_list :
			if resources_type == DictsResourcesType :
				resource_name = os.path.basename(resources_files_list_item)[:-len(DictsResourcesPostfix)]
			elif resources_type == SoundsResourcesType :
				resource_name = os.path.basename(resources_files_list_item)[:-len(SoundsResourcesPostfix)]

			try :
				if resource_name[0] == "." :
					continue
			except : continue

			try :
				resource_file_size = ftp.size(resources_files_list_item)
				if resource_file_size <= 0 :
					print >> sys.stderr, "--- resource \"%s\" :: warning, non-positive size" % (resource_name)
					continue
			except Exception, err1 :
				print >> sys.stderr, "--- resource \"%s\" :: warning, error while getting size: %s" % (resource_name, str(err1))
				continue

			remote_resources_list.append({
					"resource_name" : resource_name,
					"resource_type" : resources_type,
					"file_path" : resources_files_list_item,
					"file_size" : resource_file_size,
					"server" : repos_item["server"],
					"port" : int(repos_item["port"]),
					"user" : repos_item["user"],
					"passwd" : repos_item["passwd"]
				})

			resources_count += 1

		try :
			print "--- server \"%s\" -> %s" % (repos_item["server"], ftp.quit())
		except Exception, err1 :
			print >> sys.stderr, "--- server \"%s\" :: warning, error while closing ftp: %s" % (repos_item["server"], str(err1))

		print "--- server \"%s\" :: %d resources" % (repos_item["server"], resources_count)

		print "Remote repository \"%s\" complete ^_^\n" % (repos_item["server"])

	sort_resources_list(remote_resources_list)

	return remote_resources_list

def get_local_resources_list(resources_type) :
	if not resources_type in AllResourcesTypes :
		return []

	###

	print "Processing local repository..."
	try :
		if resources_type == DictsResourcesType :
			resources_files_list = [ os.path.join(DictsDir, item) for item in os.listdir(DictsDir) ]
		elif resources_type == SoundsResourcesType :
			resources_files_list = [ os.path.join(SoundsDir, item) for item in os.listdir(SoundsDir) ]
	except Exception, err1 :
		print >> sys.stderr, "Error while processing local repository: %s\n" % (str(err1))
		return []

	local_resources_list = []
	resources_count = 0

	for resources_files_list_item in resources_files_list :
		resource_name = os.path.basename(resources_files_list_item)

		try :
			if resource_name[0] == "." :
				continue
		except : continue

		if resources_type == DictsResourcesType :
			try :
				resource_file_size = os.stat(resources_files_list_item).st_size
				if resource_file_size <= 0 :
					print >> sys.stderr, "--- resource \"%s\" :: warning, non-positive size" % (resource_name)
					continue
			except Exception, err1 :
				print >> sys.stderr, "--- resource \"%s\" :: warning, error while getting size: %s" % (resource_name, str(err1))
				continue
		elif resources_type == SoundsResourcesType :
			try :
				resource_file_size = 0
				for root_dir_path, dirs_list, files_list in os.walk(resources_files_list_item) :
					for files_list_item in dirs_list + files_list :
						resource_file_size += os.stat(os.path.join(root_dir_path, files_list_item)).st_size
				if resource_file_size <= 0 :
					print >> sys.stderr, "--- resource \"%s\" :: warning, non-positive size" % (resource_name)
					continue
			except Exception, err1 :
				print >> sys.stderr, "--- resource \"%s\" :: warning, error while getting size: %s" % (resource_name, str(err1))
				continue

		local_resources_list.append({
				"resource_name" : resource_name,
				"resource_type" : resources_type,
				"file_path" : resources_files_list_item,
				"file_size" : resource_file_size
			})

		resources_count += 1

	print "--- local :: %d resources" % (resources_count)

	print "Local repository complete ^_^\n"

	sort_resources_list(local_resources_list)

	return local_resources_list


#####
def print_resources_list(resources_type, repositories_type) :
	if (not resources_type in AllResourcesTypes) or (not repositories_type in AllRepositoriesTypes) :
		return -1

	###

	if repositories_type == RemoteRepositoriesType :
		requested_resources_list = get_remote_resources_list(resources_type)
		installed_resources_names_list = [ item["resource_name"] for item in get_local_resources_list(resources_type) ]
	elif repositories_type == LocalRepositoriesType :
		requested_resources_list = get_local_resources_list(resources_type)
		installed_resources_names_list = [ item["resource_name"] for item in requested_resources_list ]

	if len(requested_resources_list) == 0 :
		print >> sys.stderr, "No resources :-(\n"
		return -1

	###

	print "="*get_terminal_width()
	print "\tList of available %s %s resources" % (repositories_type, resources_type)
	print "="*get_terminal_width()
	print ("%4s  %-"+str(int(get_terminal_width() * 0.72))+"s %4s %6s") % ("Num", "Name", "Stat", "Size")
	print "-"*get_terminal_width()

	past_resources_names_list = []
	resources_count = 0

	for requested_resources_list_item in requested_resources_list :
		if requested_resources_list_item["resource_name"] in past_resources_names_list :
			continue

		past_resources_names_list.append(requested_resources_list_item["resource_name"])
		resources_count += 1

		resource_installed_flag = ( True if requested_resources_list_item["resource_name"] in installed_resources_names_list else False )

		print ("%4d  %-"+str(int(get_terminal_width() * 0.72))+"s %4s %6d Kb") % ( resources_count,
			requested_resources_list_item["resource_name"], ( "ins" if resource_installed_flag else "---" ),
			requested_resources_list_item["file_size"]/1024 )

	print "="*get_terminal_width()+"\n"

	return 0


#####
def make_download_handler(out_file, out_file_size) :
	def download_handler(data_block, static = [out_file_size, 0]) :
		out_file.write(data_block)
		static[1] += len(data_block)

		percent = (100.0 * static[1]) / static[0]
		short_stdout("--- retr :: [%s] %3.1f%% %6d of %d Kb" % ( ("="*int(percent/2.5))+(" "*int(40-percent/2.5)),
			percent, static[1]/1024, static[0]/1024 ))

	return download_handler

def download_resource(remote_resource, resource_file_path) :
	short_stdout("--- resource \"%s\" :: downloading..." % (remote_resource["resource_name"]))

	try :
		resource_file = open(resource_file_path, "wb")
	except Exception, err1 :
		print >> sys.stderr, "--- resource \"%s\" :: error while opening file \"%s\": %s" % (
			remote_resource["resource_name"], resource_file_path, str(err1) )
		return -1

	try :
		ftp = ftplib.FTP()
		short_stdout("--- server \"%s\" -> %s" % (remote_resource["server"], ftp.connect(remote_resource["server"], remote_resource["port"])))
		short_stdout("--- server \"%s\" -> %s" % (remote_resource["server"], ftp.login(remote_resource["user"], remote_resource["passwd"])))
		ftp.retrbinary("RETR %s" % (remote_resource["file_path"]), make_download_handler(resource_file, remote_resource["file_size"]))
	except Exception, err1 :
		try :
			resource_file.close()
		except Exception, err2 :
			print >> sys.stderr, "--- resource \"%s\" :: warning, error while closing file \"%s\": %s" % (
				remote_resource["resource_name"], resource_file_path, str(err2) )

		try :
			os.remove(resource_file_path)
		except Exception, err2 :
			print >> sys.stderr, "--- resource \"%s\" :: warning, error while removing file \"%s\": %s" % (
				remote_resource["resource_name"], resource_file_path, str(err2) )

		try :
			short_stdout("--- server \"%s\" -> %s" % (remote_resource["server"], ftp.quit()))
		except Exception, err2 :
			print >> sys.stderr, "--- server \"%s\" :: warning, error while closing ftp: %s" % (remote_resource["server"], str(err2))

		print >> sys.stderr, "--- resource \"%s\" :: error while downloading: %s" % (remote_resource["resource_name"], str(err1))
		return -1

	try :
		resource_file.close()
	except Exception, err1 :
		print >> sys.stderr, "--- resource \"%s\" :: warning, error while closing file \"%s\": %s" % (
			remote_resource["resource_name"], resource_file_path, str(err1) )

	try :
		short_stdout("--- server \"%s\" -> %s" % (remote_resource["server"], ftp.quit()))
	except Exception, err1 :
		print >> sys.stderr, "--- server \"%s\" :: warning, error while closing ftp: %s" % (remote_resource["server"], str(err1))

	short_stdout("--- resource \"%s\" :: downloading complete" % (remote_resource["resource_name"]))

	return 0

###
def uncompress_resource(resource_name, resource_type, resource_file_path) :
	if not resource_type in AllResourcesTypes :
		return -1

	###

	short_stdout("--- resource \"%s\" :: uncompressing..." % (resource_name))

	if resource_type == DictsResourcesType :
		short_stdout("--- resource \"%s\" :: bzip2 data" % (resource_name))

		if os.system("%s -df \"%s\"" % (BZip2Prog, resource_file_path)) != 0 :
			try :
				os.remove(resource_file_path[:-len(DictsResourcesPostfix)])
			except Exception, err1 :
				print >> sys.stderr, "--- resource \"%s\" :: warning, error while removing file \"%s\": %s" % (
					resource_name, resource_file_path[:-len(DictsResourcesPostfix)], str(err1) )

			print >> sys.stderr, "--- resource \"%s\" :: error while uncompressing" % (resource_name)
			return -1
	elif resource_type == SoundsResourcesType :
		short_stdout("--- resource \"%s\" :: bzip2 tar data" % (resource_name))

		if os.system("%s -xjf \"%s\" -C \"%s\"" % (TarProg, resource_file_path, SoundsDir)) != 0 :
			try :
				for root_dir_path, dirs_list, files_list in os.walk(resource_file_path[:-len(SoundsResourcesPostfix)]) :
					for files_list_item in files_list :
						os.remove(os.path.join(root_dir_path, files_list_item))
				for root_dir_path, dirs_list, files_list in os.walk(resource_file_path[:-len(SoundsResourcesPostfix)]) :
					for dirs_list_item in dirs_list :
						os.rmdir(os.path.join(root_dir_path, dirs_list_item))
				os.rmdir(resource_file_path[:-len(SoundsResourcesPostfix)])
			except Exception, err1 :
				print >> sys.stderr, "--- resource \"%s\" :: warning, error while removing folder \"%s\": %s" % (
					resource_name, resource_file_path[:-len(SoundsResourcesPostfix)], str(err1) )

			print >> sys.stderr, "--- resource \"%s\" :: error while uncompressing" % (resource_name)
			return -1

		try :
			os.remove(resource_file_path)
		except Exception, err1 :
			print >> sys.stderr, "--- resource \"%s\" :: warning, error while removing file \"%s\": %s" % (
				resource_name, resource_file_path, str(err1) )

	short_stdout("--- resource \"%s\" :: uncompressing complete" % (resource_name))

	return 0

###
def indexate_resource(resource_name, resource_type, resource_file_path) :
	if not resource_type in AllResourcesTypes :
		return -1

	###

	if resource_type == DictsResourcesType :
		short_stdout("--- resource \"%s\" :: indexating..." % (resource_name))

		tmp1_file_path = tempfile.mkstemp()[1]+"."+MyName
		tmp2_file_path = tempfile.mkstemp()[1]+"."+MyName

		if os.system("%s --print-index \"%s\" 1> \"%s\" && %s %s 1>> %s && "
			"%s --print-index \"%s\" 1> \"%s\" && %s \"%s\" >> \"%s\" && %s \"%s\" > \"%s\"" % (
			SlProg, resource_file_path, tmp1_file_path, CatProg, resource_file_path, tmp1_file_path,
			SlProg, tmp1_file_path, tmp2_file_path, CatProg, resource_file_path, tmp2_file_path,
			CatProg, tmp2_file_path, resource_file_path)) != 0 :
			try :
				os.remove(tmp1_file_path)
			except Exception, err1 :
				print >> sys.stderr, "--- resource \"%s\" :: warning, error while removing file \"%s\": %s" % (
					resource_name, tmp1_file_path, str(err1) )

			try :
				os.remove(tmp2_file_path)
			except Exception, err1 :
				print >> sys.stderr, "--- resource \"%s\" :: warning, error while removing file \"%s\": %s" % (
					resource_name, tmp2_file_path, str(err1) )

			print >> sys.stderr, "--- resource \"%s\" :: error while indexating" % (resource_name)
			return -1

		try :
			os.remove(tmp1_file_path)
		except Exception, err1 :
			print >> sys.stderr, "--- resource \"%s\" :: warning, error while removing file \"%s\": %s" % (
				resource_name, tmp1_file_path, str(err1) )

		try :
			os.remove(tmp2_file_path)
		except Exception, err1 :
			print >> sys.stderr, "--- resource \"%s\" :: warning, error while removing file \"%s\": %s" % (
				resource_name, tmp2_file_path, str(err1) )
	elif resource_type == SoundsResourcesType :
		pass # no index-like procedure required

	short_stdout("--- resource \"%s\" :: indexating complete" % (resource_name))

	return 0

#####
def install_resources(requested_resources_names_list, resources_type) :
	if not resources_type in AllResourcesTypes :
		return -1

	###

	remote_resources_list = get_remote_resources_list(resources_type)
	if len(remote_resources_list) == 0 :
		print >> sys.stderr, "No resources :-(\n"
		return -1

	local_resources_names_list = [ local_resources_list_item["resource_name"]
		for local_resources_list_item in get_local_resources_list(resources_type) ]

	###

	print "Analysis of the request..."

	past_resources_names_list = []
	requested_resources_size = 0
	requested_resources_count = 0

	count = 0
	while count < len(remote_resources_list) :
		if remote_resources_list[count]["resource_name"] in local_resources_names_list :
			remote_resources_list.pop(count)
			continue

		if remote_resources_list[count]["resource_name"] in past_resources_names_list :
			count += 1
			continue

		if remote_resources_list[count]["resource_name"] in requested_resources_names_list or "all" in requested_resources_names_list :
			past_resources_names_list.append(remote_resources_list[count]["resource_name"])
			requested_resources_size += remote_resources_list[count]["file_size"]
			requested_resources_count += 1

		count += 1

	for requested_resources_names_list_item in requested_resources_names_list :
		if requested_resources_names_list_item in local_resources_names_list :
			print >> sys.stderr, "--- resource \"%s\" :: is already installed" % (requested_resources_names_list_item)

	if requested_resources_count == 0 :
		print >> sys.stderr, "No appropriate resources\n"
		return 0

	print "OK, %.2f Mb in %d resources for downloading" % (requested_resources_size/1048576.0, requested_resources_count)
	sys.stdout.write("Continue? [y/n]: ")
	sys.stdout.flush()
	answer = raw_input()
	if answer.lower() != "y" and answer.lower() != "yes" :
		print
		return 0
	print

	###

	past_resources_names_list = []

	for remote_resources_list_item in remote_resources_list :
		if remote_resources_list_item["resource_name"] in past_resources_names_list :
			continue

		if remote_resources_list_item["resource_name"] in requested_resources_names_list or "all" in requested_resources_names_list :
			short_stdout("--- resource \"%s\" :: begining installation..." % (remote_resources_list_item["resource_name"]))

			if resources_type == DictsResourcesType :
				compressed_resource_file_path = os.path.join(DictsDir, os.path.basename(remote_resources_list_item["file_path"]))
				resource_file_path = compressed_resource_file_path[0:-len(DictsResourcesPostfix)]
			elif resources_type == SoundsResourcesType :
				compressed_resource_file_path = os.path.join(SoundsDir, os.path.basename(remote_resources_list_item["file_path"]))
				resource_file_path = compressed_resource_file_path[0:-len(SoundsResourcesPostfix)]

			if download_resource(remote_resources_list_item, compressed_resource_file_path) != 0 :
				print >> sys.stderr, "--- resource \"%s\" :: installation failure" % (remote_resources_list_item["resource_name"])
				continue

			if uncompress_resource(remote_resources_list_item["resource_name"], resources_type, compressed_resource_file_path) != 0 :
				try :
					os.remove(compressed_resource_file_path)
				except Exception, err1 :
					print >> sys.stderr, "--- resource \"%s\" :: warning, error while removing file \"%s\": %s" % (
						remote_resources_list_item["resource_name"], compressed_resource_file_path, str(err1) )

				print >> sys.stderr, "--- resource \"%s\" :: installation failure" % (remote_resources_list_item["resource_name"])

			if indexate_resource(remote_resources_list_item["resource_name"], resources_type, resource_file_path) != 0 :
				try :
					os.remove(resource_file_path)
				except Exception, err1 :
					print >> sys.stderr, "--- resource \"%s\" :: warning, error while removing file \"%s\": %s" % (
						remote_resources_list_item["resource_name"], resource_file_path, str(err1) )

				print >> sys.stderr, "--- resource \"%s\" :: installation failure" % (remote_resources_list_item["resource_name"])

			past_resources_names_list.append(remote_resources_list_item["resource_name"])

			print "--- resource \"%s\" :: installation complete" % (remote_resources_list_item["resource_name"])

	return 0

def remove_resources(requested_resources_names_list, resources_type) :
	if not resources_type in AllResourcesTypes :
		return -1

	###

	local_resources_names_list = [ local_resources_list_item["resource_name"]
		for local_resources_list_item in get_local_resources_list(resources_type) ]

	print "Analysis of the request..."

	count = 0
	while count < len(requested_resources_names_list) :
		if not requested_resources_names_list[count] in local_resources_names_list :
			print >> sys.stderr, "--- resource \"%s\" :: is already removed" % (requested_resources_names_list[count])
			requested_resources_names_list.pop(count)
			continue
		count += 1

	if count == 0 :
		print >> sys.stderr, "No appropriate resources\n"
		return 0

	print "OK, %d resources for removing" % (count)
	sys.stdout.write("Continue? [y/n]: ")
	sys.stdout.flush()
	answer = raw_input()
	if answer.lower() != "y" and answer.lower() != "yes" :
		print
		return 0
	print

	###

	past_resources_names_list = []

	for requested_resources_names_list_item in requested_resources_names_list :
		if requested_resources_names_list_item in past_resources_names_list :
			continue

		short_stdout("--- resource \"%s\" :: begining removing..." % (requested_resources_names_list_item))

		if resources_type == DictsResourcesType :
			try :
				os.remove(os.path.join(DictsDir, requested_resources_names_list_item))
			except Exception, err1 :
				print >> sys.stderr, "--- resource \"%s\" :: removing failure: %s\n" % (requested_resources_names_list_item, str(err1))
				continue
		elif resources_type == SoundsResourcesType :
			try :
				requested_resources_names_list_item = os.path.join(SoundsDir, requested_resources_names_list_item)
				for root_dir_path, dirs_list, files_list in os.walk(requested_resources_names_list_item) :
					for files_list_item in files_list :
						os.remove(os.path.join(root_dir_path, files_list_item))
				for root_dir_path, dirs_list, files_list in os.walk(requested_resources_names_list_item) :
					for dirs_list_item in dirs_list :
						os.rmdir(os.path.join(root_dir_path, dirs_list_item))
				os.rmdir(requested_resources_names_list_item)
			except Exception, err1 :
				print >> sys.stderr, "--- resource \"%s\" :: removing failure: %s\n" % (requested_resources_names_list_item, str(err1))
				continue

		past_resources_names_list.append(requested_resources_names_list_item)

		print "--- resource \"%s\" :: removing complete" % (requested_resources_names_list_item)

	return 0

#####
def help() :
	version()
	print
	print "Remote repository commands:"
	print "\t%s %s %s" % (MyName, RemoteListCommand, DictsResourcesType)
	print "\t%s %s %s" % (MyName, RemoteListCommand, SoundsResourcesType)
	print "\t%s %s %s <file1> <file2> <fileN>" % (MyName, InstallCommand, DictsResourcesType)
	print "\t%s %s %s <file1> <file2> <fileN>" % (MyName, InstallCommand, SoundsResourcesType)
	print "Local repository commands:"
	print "\t%s %s %s" % (MyName, LocalListCommand, DictsResourcesType)
	print "\t%s %s %s" % (MyName, LocalListCommand, SoundsResourcesType)
	print "\t%s %s %s <file1> <file2> <fileN>" % (MyName, RemoveCommand, DictsResourcesType)
	print "\t%s %s %s <file1> <file2> <fileN>" % (MyName, RemoveCommand, SoundsResourcesType)
	print "Information commands:"
	print "\t%s %s" % (MyName, HelpCommand)
	print "\t%s %s" % (MyName, VersionCommand)
	print

def version() :
	print "%s-%s, Copyright (C) 2007-2016 Devaev Maxim, %s" % (MyName, Version, DeveloperMail)


##### Main #####
if __name__ == "__main__" :
	if len(sys.argv) < 2 :
		help()
		sys.exit(1)

	if not sys.argv[1] in AllCommands :
		print >> sys.stderr, "Unknown command \"%s\", try \"%s %s\"" % (sys.argv[1], MyName, HelpCommand)
		sys.exit(1)

	if sys.argv[1] == HelpCommand :
		help()

	elif sys.argv[1] == VersionCommand :
		version()

	elif sys.argv[1] == RemoteListCommand :
		if len(sys.argv) < 3 :
			print >> sys.stderr, "Command \"%s\" requires resource type" % (sys.argv[1])
			sys.exit(1)
		if not sys.argv[2] in AllResourcesTypes :
			print >> sys.stderr, "Unknown resource type \"%s\"" % (sys.argv[2])
			sys.exit(1)
		sys.exit( 1 if print_resources_list(sys.argv[2], RemoteRepositoriesType) != 0 else 0 )

	elif sys.argv[1] == LocalListCommand :
		if len(sys.argv) < 3 :
			print >> sys.stderr, "Command \"%s\" requires resource type" % (sys.argv[1])
			sys.exit(1)
		if not sys.argv[2] in AllResourcesTypes :
			print >> sys.stderr, "Unknown resource type \"%s\"" % (sys.argv[2])
			sys.exit(1)
		sys.exit( 1 if print_resources_list(sys.argv[2], LocalRepositoriesType) != 0 else 0 )

	elif sys.argv[1] == InstallCommand :
		if len(sys.argv) < 3 :
			print >> sys.stderr, "Command \"%s\" requires resource type" % (sys.argv[1])
			sys.exit(1)
		if not sys.argv[2] in AllResourcesTypes :
			print >> sys.stderr, "Unknown resource type \"%s\"" % (sys.argv[2])
			sys.exit(1)
		if len(sys.argv) < 4 :
			print >> sys.stderr, "Minimum one file required for command \"%s\"" % (sys.argv[1])
			sys.exit(1)
		sys.exit( 1 if install_resources(sys.argv[3:], sys.argv[2]) != 0 else 0 )

	elif sys.argv[1] == RemoveCommand :
		if len(sys.argv) < 3 :
			print >> sys.stderr, "Command \"%s\" requires resource type" % (sys.argv[1])
			sys.exit(1)
		if not sys.argv[2] in AllResourcesTypes :
			print >> sys.stderr, "Unknown resource type \"%s\"" % (sys.argv[2])
			sys.exit(1)
		if len(sys.argv) < 4 :
			print >> sys.stderr, "Minimum one file required for command \"%s\"" % (sys.argv[1])
			sys.exit(1)
		sys.exit( 1 if remove_resources(sys.argv[3:], sys.argv[2]) != 0 else 0 )

