#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright © 2017, François Laurent

# This file is part of the Escale software available at
# "https://github.com/francoislaurent/escale" and is distributed under
# the terms of the CeCILL-C license as circulated at the following URL
# "http://www.cecill.info/licenses.en.html".

# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL-C license and that you accept its terms.


import argparse
import sys
from escale import *
from escale.cli.ctl import *
from escale.cli.license import *
from escale.base.exceptions import LicenseError, ExpressInterrupt


def chmod(modifiers=None, resource=None, repository=None):
	if modifiers:
		if isinstance(modifiers, list):
			modifiers = ''.join(modifiers)
	else:
		modifiers = None
	try:
		result = access(modifiers=modifiers, resource=resource, repository=repository)
	except Exception as e:
		return e
	else:
		if not modifiers:
			print(result)


if __name__ == '__main__':
	parser = argparse.ArgumentParser(prog=PROGRAM_NAME+'ctl',
		description='Escale - Client-to-client synchronization based on external relay storage',
		epilog='See also escale')
	parser.add_argument('-y', '--accept-license', action='store_true', help='skip the license acceptance step at first startup and agree with the terms of the license')
	parsers = parser.add_subparsers(title='command')
	_start = parsers.add_parser('start', help='start {} in daemon mode'.format(PROGRAM_NAME))
	_start.set_defaults(func=start)
	_stop = parsers.add_parser('stop', help='stop all {} instances'.format(PROGRAM_NAME))
	_stop.set_defaults(func=stop)
	_restart = parsers.add_parser('restart', help='restart all {} instances'.format(PROGRAM_NAME))
	_restart.set_defaults(func=restart)
	_chmod = parsers.add_parser('access', help='change permissions of file')
	_chmod.add_argument('-r', '--repository', type=str, metavar='NAME', help='file repository')
	_chmod.add_argument('resource', type=str, help='path to local file')
	_chmod.add_argument('modifiers', type=str, nargs='*', help="any combination of 'r', 'r-', 'r?', 'w', 'w-', 'w?'")
	_chmod.set_defaults(func=chmod)
	_migrate = parsers.add_parser('migrate', help='migrate a relay repository from a host to another')
	_migrate.add_argument('-f', '--fast', action='store_true', help='unsafe copy; use this only if repository is inactive')
	_migrate.add_argument('-r', '--repository', type=str, metavar='NAME', help='source repository')
	_migrate.add_argument('destination', type=str, help='path to configuration file or address of the destination relay')
	_migrate.set_defaults(func=migrate)
	_backup = parsers.add_parser('backup', help='backup a relay repository to an archive')
	_backup.add_argument('repository', type=str, help='section in the default configuration file')
	_backup.add_argument('archive', type=str, help='path to archive (.tar, .tar.gz or .tar.bz2)')
	_backup.add_argument('-f', '--fast', action='store_true', help='unsafe copy; use this only if repository is inactive')
	_backup.set_defaults(func=backup)
	_restore = parsers.add_parser('restore', help='restore a relay repository from a backup archive')
	_restore.add_argument('repository', type=str, help='section in the default configuration file')
	_restore.add_argument('archive', type=str, help='path to archive (.tar, .tar.gz or .tar.bz2)')
	_restore.add_argument('-f', '--fast', action='store_true', help='unsafe copy; use this only if repository is inactive')
	_restore.set_defaults(func=restore)
	_fix = parsers.add_parser('fix', help='recover a lost relay repository from an up-to-date local repository')
	_fix.add_argument('-r', '--repository', type=str, help='section in the default configuration file')
	_fix.add_argument('-u', '--update', action='store_true', help='do not overwrite')
	_fix.add_argument('-f', '--fast', action='store_true', help='unsafe recovery; use this only if repository is inactive')
	_fix.add_argument('-p', '--page', nargs='+', help='recover a single index page; for indexed repository only')
	_fix.set_defaults(func=recover)
	_rebase = parsers.add_parser('rebase', help='rebase an existing relay repository as a sub-directory in the new relay repository (index-based only)')
	_rebase.add_argument('-r', '--repository', type=str, metavar='NAME', help='section in the default configuration file')
	_rebase.add_argument('extra_path', type=str, help='path elements to append as extra upper levels to the existing relay repository path')
	_rebase.set_defaults(func=rebase)
	_suspend = parsers.add_parser('suspend', help='suspend synchronization of index-based repositories')
	_suspend.add_argument('-r', '--repository', type=str, metavar='SECTION', help='section in the default configuration file')
	_suspend.add_argument('-p', '--page', type=str, metavar='PAGE', help='specific index page')
	_suspend.set_defaults(func=suspend)
	_resume = parsers.add_parser('resume', help='resume synchronization of index-based repositories after suspend')
	_resume.add_argument('-r', '--repository', type=str, metavar='SECTION', help='section in the default configuration file')
	_resume.add_argument('-p', '--page', type=str, metavar='PAGE', help='specific index page')
	_resume.set_defaults(func=resume)
	_make_cache = parsers.add_parser('make-cache', help='make local checksum cache')
	_make_cache.add_argument('-r', '--repository', type=str, metavar='SECTION', help='section in the default configuration file')
	_make_cache.set_defaults(func=make_cache)
	_clear_cache = parsers.add_parser('clear-cache', help='clear local checksum cache')
	_clear_cache.add_argument('-r', '--repository', type=str, metavar='SECTION', help='section in the default configuration file')
	_clear_cache.set_defaults(func=clear_cache)
	_list_pending = parsers.add_parser('list-pending', help='list local files pending for upload')
	_list_pending.add_argument('-r', '--repository', type=str, metavar='SECTION', help='section in the default configuration file')
	_list_pending.add_argument('-p', '--page', type=str, metavar='PAGE', help='specific index page')
	_list_pending.add_argument('-d', '--directories', action='store_true', help='show subdirectories instead of files')
	_list_pending.set_defaults(func=list_pending)
	args = parser.parse_args()
	ret = 0
	try:
		check_license_acceptance(args.accept_license)
	except LicenseError as e:
		print(str(e))
		sys.exit(ret)
	try:
		args.func
	except ExpressInterrupt:
		pass
	except AttributeError:
		parser.print_help()
	else:
		args = args.__dict__
		del args['accept_license']
		func = args.pop('func')
		ret = func(**args)
	sys.exit(ret)

