/*
 * Copyright 2023 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include "applauncherdaemon.h"
#include <QSocketNotifier>
#include <QCoreApplication>
#include <QDBusConnection>
#include <QDBusInterface>
#include <QDBusPendingCall>
#include <QDebug>

extern "C" {
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/prctl.h>
}

int AppLauncherDaemon::s_sigChldFd[2];
int AppLauncherDaemon::s_sigQuitFd[2];

AppLauncherDaemon::AppLauncherDaemon(QObject *parent)
    : QObject(parent)
    , m_logoutInhibitCookie(0)
{
    // when app starts with '&' in shell, AppManager takes over it.
    if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0) {
        qWarning() << "Failed to make us a subreaper: " << strerror(errno);
    }

    if (::socketpair(AF_UNIX, SOCK_STREAM, 0, s_sigChldFd)) {
        qFatal("Couldn't create CHLD socketpair");
    }
    if (::socketpair(AF_UNIX, SOCK_STREAM, 0, s_sigQuitFd)) {
        qFatal("Couldn't create Quit socketpair");
    }

    m_snChld = new QSocketNotifier(s_sigChldFd[1], QSocketNotifier::Read, this);
    m_snQuit = new QSocketNotifier(s_sigQuitFd[1], QSocketNotifier::Read, this);

    connect(m_snChld, &QSocketNotifier::activated, this, &AppLauncherDaemon::handleSigChld);
    connect(m_snQuit, &QSocketNotifier::activated, this, &AppLauncherDaemon::handleQuitSig);

    connect(qApp, &QCoreApplication::aboutToQuit, this, &AppLauncherDaemon::aboutToQuitAppManager);

    setupUnixSignalHandlers();


    bool shutDownConnection = QDBusConnection::systemBus().connect("org.freedesktop.login1",
                                                                   "/org/freedesktop/login1/Manager",
                                                                   "org.freedesktop.login1.Manager",
                                                                   "PrepareForShutdown",
                                                                   this,
                                                                   SLOT(prepareForShutdown(bool)));
    if (!shutDownConnection) {
        qWarning() << "connect to PrepareForShutdown failed!";
    }

    /// FIXME
#if 0
    m_sessionmanagerInterface = new QDBusInterface("org.gnome.SessionManager",
                                   "/org/gnome/SessionManager",
                                   "org.gnome.SessionManager",
                                   QDBusConnection::sessionBus());
    auto reply = m_sessionmanagerInterface->asyncCallWithArgumentList("Inhibit",
                                                           QVariantList() << "kylin-app-manager"
                                                           << quint32(0)
                                                           << "Delete CGroups" << quint32(1));

    reply.waitForFinished();
    if (reply.isError()) {
        qDebug() << "Add Inhibit Error: " << reply.error();
    } else {
        m_logoutInhibitCookie = reply.reply().arguments().first().toUInt();
        qDebug() << "m_logoutInhibitCookie " << m_logoutInhibitCookie;
    }
#endif
}

void AppLauncherDaemon::chldSignalHandler(int unused)
{
    Q_UNUSED(unused)
    char a = 1;
    ::write(s_sigChldFd[0], &a, sizeof(a));
}

void AppLauncherDaemon::quitSignalHandler(int unused)
{
    Q_UNUSED(unused)
#ifdef QT_DEBUG
    qDebug() << "handle linux signal: " << unused;
#endif
    char a = 1;
    ::write(s_sigQuitFd[0], &a, sizeof(a));
}

void AppLauncherDaemon::setupUnixSignalHandlers()
{
    struct sigaction chld, term, inter;

    chld.sa_handler = AppLauncherDaemon::chldSignalHandler;
    sigemptyset(&chld.sa_mask);
    chld.sa_flags = 0;
    chld.sa_flags |= SA_RESTART;
    if (sigaction(SIGCHLD, &chld, 0)) {
        qWarning() << "handle SIGCHLD failed: " << errno;
    }

    term.sa_handler = AppLauncherDaemon::quitSignalHandler;
    sigemptyset(&term.sa_mask);
    term.sa_flags = 0;
    term.sa_flags |= SA_RESTART;
    if (sigaction(SIGTERM, &term, 0)) {
        qWarning() << "handle SIGTERM failed: " << errno;
    }

    inter.sa_handler = AppLauncherDaemon::quitSignalHandler;
    sigemptyset(&inter.sa_mask);
    inter.sa_flags = 0;
    inter.sa_flags |= SA_RESTART;
    if (sigaction(SIGINT, &inter, 0)) {
        qWarning() << "handle SIGINT failed: " << errno;
    }
}

void AppLauncherDaemon::handleSigChld()
{
    m_snChld->setEnabled(false);
    char tmp;
    ::read(s_sigChldFd[1], &tmp, sizeof(tmp));

    int pid = waitpid(-1, NULL, WNOHANG);
    // No child processes. Case of starting with QProcess

    // When the app launches with QProcess, waitpid() would return -1
    // and set errno 10 what means "No child process".
    // Startup with "&" with QProcess in shell,
    // waitpid() would return the child process id.
    if (pid > 0) {
        Q_EMIT childProcessFinished(pid);
    }

    m_snChld->setEnabled(true);
}

void AppLauncherDaemon::handleQuitSig()
{
    m_snChld->setEnabled(false);
    char tmp;
    ::read(s_sigQuitFd[1], &tmp, sizeof(tmp));

    qDebug() << "handle quit sig";

    Q_EMIT aboutToQuitAppManager();

    m_snChld->setEnabled(true);
    qApp->quit();
}

void AppLauncherDaemon::prepareForShutdown(bool shutDown)
{
    if (shutDown) {
        qDebug() << "About to shutdown";
        Q_EMIT aboutToQuitAppManager();
#if 0
        m_sessionmanagerInterface->asyncCallWithArgumentList("Uninhibit",
                                                             QVariantList() << m_logoutInhibitCookie);
#endif
    }
}
