#!/opt/alt/python37/bin/python3

# Copyright (c) Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2018 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

import os.path
from datetime import datetime

try:
    from raven import Client
except ImportError:
    exit(1)


def make_file_to_process():
    """
    Rename message file into message-%Y%m%d-%H%M%S.%f to process log
    """
    log_path = "/var/log/mod_lsapi/messages"
    if not os.path.isfile(log_path):
        return None

    now = datetime.now().strftime("-%Y%m%d-%H%M%S.%f")
    fname = log_path + now
    os.rename(log_path, fname)
    return fname


def process_file(fname):
    """ 
    Get list of logged messages from new log file
    """
    with open(fname) as f:
        content = f.readlines()

    content = [x.strip() for x in content if x.strip()]
    res = []
    for s in content:
        res.append(s.split('\001'))
    return res 


def process_list(content, client):
    """ 
    Send each message from content to sentry
    """
    for message in content:
        client.capture('raven.events.Message', message=message[0], data={
            'request': {
                'method': 'POST',
            },
        }, extra={
            'Detailed info': message[1],
        })


def main():
    """
    Run main actions
    """
    dns = "https://ce7a4f9a50974f47ace1b4140b0594a5:8e39499e5b1243259739bebe91d5c6bb@sentry.cloudlinux.com/2"
    client = Client(dns)
    if not client:
        exit(1)

    fname = make_file_to_process()
    if not fname:
        exit(0)

    content = process_file(fname)
    if not content:
        exit(0)

    process_list(content, client)


if "__main__" == __name__:
    main()

