#!/usr/bin/env python3
import argparse
import configparser
import json
import logging
import time
from datetime import datetime
from logging.handlers import SysLogHandler
from operator import itemgetter

import duo_client
from tzlocal import get_localzone


def get_logs(mintime):
    logs = []
    admin_api = duo_client.Admin(
        ikey=INTEGRATION_KEY, skey=SECRET_KEY, host=API_HOST)
    if AUTHENTICATION:
        logs.extend(admin_api.get_authentication_log(mintime=mintime))
    if ADMINISTRATOR:
        logs.extend(admin_api.get_administrator_log(mintime=mintime))
    if TELEPHONY:
        logs.extend(admin_api.get_telephony_log(mintime=mintime))
    logs.sort(key=itemgetter('timestamp'))
    return logs


def run_logger():
    current_time = int(time.time())
    mintime = current_time - DELTA
    logs = get_logs(mintime)
    for log in logs:
        timestamp = datetime.fromtimestamp(log.get('timestamp'), get_localzone()).isoformat()
        log_message = '1 {} {} Duo - - - {}'.format(timestamp, API_HOST, json.dumps(log, sort_keys=True))
        if DEBUG:
            print(log_message)
        else:
            LOGGER.info(log_message)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Pull Duo Security logs from Duo Admin API.',
                                     epilog='https://duo.com/docs/adminapi#logs')
    parser.add_argument('-c', '--config_file', help='configuration file', required=True)
    args = parser.parse_args()

    config = configparser.ConfigParser()
    config.read(args.config_file)
    DEBUG = config.getboolean('main', 'DEBUG')
    SYSLOG_SERVER = config.get('main', 'SYSLOG_SERVER')
    INTEGRATION_KEY = config.get('api', 'INTEGRATION_KEY')
    SECRET_KEY = config.get('api', 'SECRET_KEY')
    API_HOST = config.get('api', 'API_HOST')
    DELTA = config.getint('logs', 'DELTA')  # Retrieve all messages within these seconds
    AUTHENTICATION = config.getboolean('logs', 'AUTHENTICATION')
    ADMINISTRATOR = config.getboolean('logs', 'ADMINISTRATOR')
    TELEPHONY = config.getboolean('logs', 'TELEPHONY')

    LOGGER = logging.getLogger()
    LOGGER.setLevel(logging.INFO)

    syslog = SysLogHandler(address=(SYSLOG_SERVER, 514))
    LOGGER.addHandler(syslog)

    run_logger()
