/* SPDX-License-Identifier: LGPL-2.1-or-later */

#include <locale.h>
#include <unistd.h>
#include <fcntl.h>
#include <syslog.h>
#include <string.h>
#include <stdio.h>

#include "alloc-util.h"
#include "process-util.h"
#include "log.h"
#include "strv.h"
#include "bus-error.h"
#include "edit-util.h"
#include "fs-util.h"
#include "pager.h"
#include "path-util.h"
#include "pretty-print.h"
#include "selinux-util.h"
#include "terminal-util.h"
#include "comm-util.h"

void print_caller(const char *method, char **names)
{
        pid_t ppid = getppid();
        pid_t pppid = -1;
        pid_t ppppid = -1;
        _cleanup_free_ char *comm = NULL, *pcomm = NULL, *ppcomm = NULL;
        if (ppid > 0) {
                pid_get_comm(ppid, &comm);
                pppid = find_parent_pid(ppid);
                if (pppid > 0) {
                        pid_get_comm(pppid, &pcomm);
                        ppppid = find_parent_pid(ppid);
                        if (ppppid > 0)
                                pid_get_comm(ppppid, &ppcomm);
                }
        }
        if (names) {
                STRV_FOREACH(name, names) {
                        log_debug("systemctl %s %s, by comm:%s pid:%d, pcomm:%s, pppid:%d, ppcomm:%s, ppppid:%d",
                                method, *name, comm, ppid,  pcomm, pppid, ppcomm, ppppid);
                        syslog(LOG_INFO,"systemctl %s %s, by comm:%s pid:%d, pcomm:%s, pppid:%d, ppcomm:%s, ppppid:%d",
                                method, *name, comm, ppid, pcomm, pppid, ppcomm, ppppid);
                }
        } else {
                log_debug("systemctl %s, by comm:%s pid:%d, pcomm:%s, pppid:%d, ppcomm:%s, ppppid:%d",
                        method, comm, ppid,  pcomm, pppid, ppcomm, ppppid);
                syslog(LOG_INFO, "systemctl %s, by comm:%s pid:%d, pcomm:%s, pppid:%d, ppcomm:%s, ppppid:%d",
                        method, comm, ppid, pcomm, pppid, ppcomm, ppppid);
        }
}
