#!/bin/python3

import re
import os

# File path to the target script file
cleanup_file_path = "/etc/cron.d/perfact-cleanup"
transport_closed_file_path = "/etc/postfix/transport_closed"

# Patterns for the lines to be deleted
patterns_to_delete = [
    re.compile(r"# If cockpit as active, a fuse mount is \
               created in a hidden folder in /tmp,"),
    re.compile(r"# which root can not access\. For this reason, \
               we need to use ls and can not use"),
    re.compile(r".*/2.*root.*for i in.*do test -d /tmp/.*-maxdepth \
               0 -mmin.*5 -exec rm -rf {}.*done"),
    re.compile(r".*/2.*root.*find /tmp/ -mindepth 1 -maxdepth 1 -type \
               d -name.* -mmin.*2>/dev/null"),
]
# This is used to replace a static crontab entry for /tmp file cleanup
# with a more generic one as part of the perfact-system-tools debian package
if os.path.exists(cleanup_file_path):
    # Search and delete lines in the file
    with open(cleanup_file_path, "r") as file:
        lines = file.readlines()

    with open(cleanup_file_path, "w") as file:
        for line in lines:
            if not any(re.match(pattern, line) for pattern in
                       patterns_to_delete):
                file.write(line)

# This is used to add admins in transport_closed
if os.path.exists(transport_closed_file_path):
    relay = False
    contains = False

    with open(transport_closed_file_path, "r") as file:
        contents = file.read()
        if "relay" in contents:
            relay = True
        if "admins@perfact.de" in contents:
            contains = True

    if not contains:
        with open(transport_closed_file_path, "a") as file:
            if relay:
                file.write(
                    "admins@perfact.de relay:[" +
                    os.popen("postconf -n relayhost")
                    .read().split("=")[1].strip() + "]"
                )
            else:
                file.write("admins@perfact.de :")
        os.system("postmap /etc/postfix/transport_closed")
