#!/usr/bin/python

import argparse
import sys
import os
import logging
from repodeploy import config, Deployer


if __name__ == '__main__':

	parser = argparse.ArgumentParser()
	parser.add_argument('-c', '--config', default='/etc/repo-deploy/repo-deploy.cfg', help='Configuration file')
	parser.add_argument('--pre-hooks', default='/etc/repo-deploy/pre-update.d', help='Pre-update script hooks directory')
	parser.add_argument('--post-hooks', default='/etc/repo-deploy/post-update.d', help='Post-update script hooks directory')
	parser.add_argument('-i', '--id', help='Application identity')
	parser.add_argument('-d', '--directory', help='Deployer directory')
	parser.add_argument('-f', '--fetch', action='store_true', help='Fetch config once and exit')
	parser.add_argument('-v', '--verbose', action='store_true', help='Verbose logging for debugging')
	args = parser.parse_args()

	if not os.path.exists(args.config):
		sys.stderr.write('Unable to find config file')
		sys.exit(1)

	cfg = config.instance_config(config.parse(args.config))

	if not 'repository' in cfg:
		sys.stderr.write('No configuration repository specified')
		sys.exit(1)

	repository = cfg['repository']

	if args.id:
		cfg['identity'] = args.id
	if args.directory:
		cfg['directory'] = args.directory
	cfg['pre_hooks'] = args.pre_hooks
	cfg['post_hooks'] = args.post_hooks

	if args.verbose:
		logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s:%(lineno)d %(message)s')
	else:
		logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s:%(lineno)d %(message)s')

	if args.fetch:
		if not Deployer(cfg).check_config():
			sys.stderr.write('No configuration found')
			sys.exit(1)
	else:
		Deployer(cfg).run()
