#!/usr/bin/python3.6

import argparse
import os
import sys
import logging

# ARC-prefix path in PYTHONPATH
arc_prefix_pythonpath = '${prefix}/lib64/python3.6/site-packages'.replace('${prefix}', '/usr')
if os.path.isdir(arc_prefix_pythonpath):
    if arc_prefix_pythonpath not in sys.path:
        sys.path.insert(1, arc_prefix_pythonpath)

from arc.utils import config
from arc.control import AccountingPublishing

# Initialize logging
logger = logging.getLogger('ARC')
logger.setLevel(logging.INFO)
log_handler_stderr = logging.StreamHandler()
log_handler_stderr.setFormatter(
    logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] [%(process)d] [%(message)s]'))
logger.addHandler(log_handler_stderr)


# Define root parser
def get_parser():
    parser = argparse.ArgumentParser(description='NorduGrid ARC Jura Next Generation Publisher')
    parser.add_argument('-c', '--config', action='store',
                        help='Config file location (default is {0})'.format(config.arcconf_defpath()))
    parser.add_argument('-d', '--debug', action='store',
                        help='Verbosity level (default is %(default)s)', default='WARNING',
                        choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'])
    return parser

if __name__ == '__main__':
    # Command line arguments parsing
    args_parser = get_parser()
    cmd_args = args_parser.parse_args()
    logger.setLevel(getattr(logging, cmd_args.debug, 30))
    # Config parsing (jura designed to be run by A-REX => runtime config provided)
    config.load_run_config(cmd_args.config)

    # Set loglevel in accordance to config
    loglevel = config.get_value('loglevel', 'arex/jura')
    if loglevel is not None:
        loglevel = int(loglevel)
        if loglevel > 5:
            loglevel = 5
        loglevel = [logging.CRITICAL,
                    logging.ERROR,
                    logging.WARNING,
                    logging.INFO,
                    logging.DEBUG,
                    logging.DEBUG][loglevel]
        logger.setLevel(loglevel)

    # Run normal regular publishing
    rp = AccountingPublishing.RecordsPublisher(config)
    rp.publish_regular()
