#!/opt/cloudlinux/venv/bin/python3

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

import os
import os.path
import stat
from datetime import datetime

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


def make_file_to_process():
    """
    Atomically rename the message file to a timestamped name for processing.

    The rename is attempted unconditionally — if the file does not exist the
    OS raises FileNotFoundError which we treat as "nothing to do".  This
    avoids the isfile→rename TOCTOU window where a symlink could be planted
    between the existence check and the rename.
    """
    log_path = "/var/log/mod_lsapi/messages"
    now = datetime.now().strftime("-%Y%m%d-%H%M%S.%f")
    fname = log_path + now
    try:
        os.rename(log_path, fname)
    except OSError:
        return None
    return fname


def process_file(fname):
    """
    Get list of logged messages from new log file.

    Opens with O_NOFOLLOW so that a symlink planted at fname after the rename
    cannot redirect the read to an attacker-chosen path.
    """
    try:
        fd = os.open(fname, os.O_RDONLY | os.O_NOFOLLOW)
    except OSError:
        return []
    if not stat.S_ISREG(os.fstat(fd).st_mode):
        os.close(fd)
        return []
    with os.fdopen(fd) 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
    """
    dsn = "https://ce7a4f9a50974f47ace1b4140b0594a5@sentry.cloudlinux.com/2"
    client = Client(dsn)
    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()

