// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
// SPDX-FileCopyrightText: 2022 Harald Sitter <sitter@kde.org>

#include "helper.h"

#include <QDebug>
#include <QFile>
#include <QProcess>

#include <KAuth/HelperSupport>

#include <entries.h>

[[nodiscard]] static bool reloadSystem()
{
    const bool ret = QProcess::execute(QStringLiteral("/usr/sbin/sysctl"), {QStringLiteral("--system")}) == 0;
    if (!ret) {
        qWarning() << "system reload failed";
    }
    return ret;
}

[[nodiscard]] static QByteArray head()
{
    return QByteArrayLiteral("# This file was auto-generated by kde-inotify-survey. Manual changes will be overwritten.\n");
}

KAuth::ActionReply INotifySurveyHelper::increaseinstancelimit(const QVariantMap &args)
{
    Q_UNUSED(args);
    const auto capacity = inotifyCapacity();
    const auto maxCapacity = maximumINotifyCapacity();
    const auto newLimit = qMin(capacity.max_user_instances + instanceStepSize(), maxCapacity.max_user_instances);
    if (QFile file(QStringLiteral("/etc/sysctl.d/50-kde-inotify-survey-max_user_instances.conf")); file.open(QFile::WriteOnly | QFile::Truncate)) {
        file.write(head());
        file.write(QStringLiteral("fs.inotify.max_user_instances=%1\n").arg(QString::number(newLimit)).toUtf8());
    } else {
        qWarning() << "Failed to open file" << file.errorString();
        return KAuth::ActionReply::HelperErrorReply();
    }
    if (!reloadSystem()) {
        return KAuth::ActionReply::HelperErrorReply();
    }
    return KAuth::ActionReply::SuccessReply();
}

KAuth::ActionReply INotifySurveyHelper::increasewatchlimit(const QVariantMap &args)
{
    Q_UNUSED(args);
    const auto capacity = inotifyCapacity();
    const auto maxCapacity = maximumINotifyCapacity();
    const auto newLimit = qMin(capacity.max_user_watches + watchStepSize(), maxCapacity.max_user_watches);
    if (QFile file(QStringLiteral("/etc/sysctl.d/50-kde-inotify-survey-max_user_watches.conf")); file.open(QFile::WriteOnly | QFile::Truncate)) {
        file.write(head());
        file.write(QStringLiteral("fs.inotify.max_user_watches=%1\n").arg(QString::number(newLimit)).toUtf8());
    } else {
        qWarning() << "Failed to open file" << file.errorString();
        return KAuth::ActionReply::HelperErrorReply();
    }
    if (!reloadSystem()) {
        return KAuth::ActionReply::HelperErrorReply();
    }
    return KAuth::ActionReply::SuccessReply();
}

KAUTH_HELPER_MAIN("org.kde.kded.inotify", INotifySurveyHelper)
