/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* Copyright 2013 - 2020, nymea GmbH
* Contact: contact@nymea.io
*
* This file is part of maveod.
* This project including source code and documentation is protected by
* copyright law, and remains the property of nymea GmbH. All rights, including
* reproduction, publication, editing and translation, are reserved. The use of
* this project is subject to the terms of a license agreement to be concluded
* with nymea GmbH in accordance with the terms of use of nymea GmbH, available
* under https://nymea.io/license
*
* For any further details and any questions please contact us under
* contact@nymea.io or see our FAQ/Licensing Information on
* https://nymea.io/license/faq
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#include "systemdservice.h"
#include "loggingcategories.h"

#include <QDBusInterface>
#include <QDBusPendingReply>

SystemdService::SystemdService(QObject *parent) : QObject(parent)
{
    qCDebug(dcSystemdService()) << "Initialize the systemd service";
    QDBusInterface logind("org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", QDBusConnection::systemBus());
    const auto message = logind.callWithArgumentList(QDBus::Block, "CanPowerOff", {});
    QDBusPendingReply<QString> canPowerOff = message;
    canPowerOff.waitForFinished();

    if (canPowerOff.isError()) {
        qCWarning(dcSystemdService()) << "DBus call to logind failed:" << canPowerOff.error().name() <<  canPowerOff.error().message();
    } else if (canPowerOff.value() == "yes") {
        qCDebug(dcSystemdService()) << "The system can be rebooted.";
    }
    qCDebug(dcNymeaService()) << "Initialized systemd D-Bus services successfully";
}

bool SystemdService::rebootSystem()
{
    qCDebug(dcSystemdService()) << "Rebooting system";
    QDBusInterface logind("org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", QDBusConnection::systemBus());
    QDBusPendingReply<> rebootReplay = logind.callWithArgumentList(QDBus::Block, "Reboot", {true, });
    rebootReplay.waitForFinished();
    if (rebootReplay.isError()) {
        qCWarning(dcSystemdService()) << "Error while calling reboot on logind." << rebootReplay.error();
        return false;
    }
    return true;
}
