#!/usr/bin/env python3

import argparse, logging
from operation import AcmeOperation

def main():
    parser     = argparse.ArgumentParser(description='Automate and store let\'s encrypt ssl certificates into S3')
    subparsers = parser.add_subparsers(dest='action')
    
    for action in ['obtain', 'auth', 'cleanup']:
       action_parser = subparsers.add_parser(action)
       action_parser.add_argument('-p', dest='provider', help='the domain name provider', action='store', required=True)
       action_parser.add_argument('--expand', dest='expand', help='updates an existing certificate with a new certificate/s', action='store_true')
       action_parser.add_argument('--test', dest='test', help='obtain a test certificate from a staging server', action='store_true')
        

    domains_parser     = subparsers.add_parser('domains')
    domains_subparsers = domains_parser.add_subparsers(dest='subaction')

    for domains_action in ['add', 'remove', 'list']:
        domain_action_parser = domains_subparsers.add_parser(domains_action)
        if domains_action in ['add', 'remove']:
            domain_action_parser.add_argument('-d', dest='domain',   help='the domain to {0}'.format(domains_action), action='store', required=True)
            domain_action_parser.add_argument('-p', dest='provider', help='the domain name provider', action='store', required=True)

    config_parser     = subparsers.add_parser('config')
    config_subparsers = config_parser.add_subparsers(dest='subaction')

    for config_action in ['certbot', 'lexicon', 'show']:
        config_action_parser = config_subparsers.add_parser(config_action)
        if config_action in ['certbot', 'lexicon']:
            config_action_parser.add_argument('-path', dest='path',   help='the path to {0}'.format(config_action), action='store', required=True)

    subparsers.add_parser('s3_upload', help='Manually uploads the live certificate files into the configured s3-compatible storage')

    try: 
        args = parser.parse_args()
        provider = None
        if hasattr(args, 'provider'):
            provider = args.provider
        operation = AcmeOperation(provider=provider)
        if args.action == 'obtain':
            operation.obtain(test=args.test, expand=args.expand)
        if args.action in ['auth', 'cleanup']:
            operation.hook(action=args.action)
        elif args.action == 'domains':
            operation.config.domainAction(args)
        elif args.action == 'config':
            operation.config.configAction(args)
        elif args.action == 's3_upload':
            operation.manual_s3_upload()
    except Exception as ex:
        logging.error(ex)        

if __name__ == '__main__':
    main()