# Copyright 1999-2013 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

import os
import time

import portage
from portage.data import secpass
from portage.output import xtermTitle

# We disable emergelog by default, since it's called from
# dblink.merge() and we don't want that to trigger log writes
# unless it's really called via emerge.
_disable = True
_emerge_log_dir = "/var/log"


def emergelog(xterm_titles, mystr, short_msg=None):
    if _disable:
        return

    if isinstance(mystr, bytes):
        mystr = mystr.decode("utf-8", "replace")

    if short_msg is not None:
        if isinstance(short_msg, bytes):
            short_msg = short_msg.decode("utf-8", "replace")

    if xterm_titles and short_msg:
        xtermTitle(short_msg)
    try:
        file_path = os.path.join(_emerge_log_dir, "emerge.log")
        existing_log = os.path.exists(file_path)
        mylogfile = open(
            file_path,
            mode="a",
            encoding="utf-8",
            errors="backslashreplace",
        )
        if not existing_log:
            portage.util.apply_secpass_permissions(
                file_path, uid=portage.portage_uid, gid=portage.portage_gid, mode=0o660
            )
        mylock = portage.locks.lockfile(file_path)
        try:
            mylogfile.write(f"{int(time.time())}: {mystr}\n")
            mylogfile.close()
        finally:
            portage.locks.unlockfile(mylock)
    except (OSError, portage.exception.PortageException) as e:
        if secpass >= 1:
            portage.util.writemsg(f"emergelog(): {e}\n", noiselevel=-1)
