/*
* Copyright (C) 2024, 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/>.
 *
 * Authors: iaom <zhangpengfei@kylinos.cn>
 *
 */

#include "inotify-config.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>

InotifyConfig::InotifyConfig(QObject* parent)
{
}

QString InotifyConfig::setInotifyMaxUserWatchesStep2()
{
    QFile file("/proc/sys/fs/inotify/max_user_watches");
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return {};
    QTextStream ts(&file);
    QString s = ts.read(512);
    file.close();
    if(s.toInt() >= 9999999 ) {
        return s;
    }

    QByteArray ba;
    char cmd[128];
    sprintf(cmd, "sysctl -w fs.inotify.max_user_watches=\"9999999\"");
    if(FILE * fp = nullptr; (fp = popen(cmd, "r")) != nullptr) {
        rewind(fp);
        while(!feof(fp)) {
            char buf[1024];
            fgets(buf, sizeof(buf), fp);
            ba.append(buf);
        }
        pclose(fp);
        fp = nullptr;
    } else {
        return {"setInotifyMaxUserWatchesStep2: popen open failed"};
    }
    return {ba};
}

int InotifyConfig::AddInotifyMaxUserInstance(int addNum)
{
    QFile file("/proc/sys/fs/inotify/max_user_instances");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return -1;
    }
    QTextStream ts(&file);
    const QString s = ts.read(512);
    file.close();
    const int instances = s.toInt() + addNum;
    char cmd[128];
    sprintf(cmd, "sysctl -w fs.inotify.max_user_instances=\"%d\"", instances);
    if (FILE* fp = nullptr; (fp = popen(cmd, "r")) != nullptr) {
        QByteArray ba;
        rewind(fp);
        while (!feof(fp)) {
            char buf[1024];
            fgets(buf, sizeof(buf), fp);
            ba.append(buf);
        }
        pclose(fp);
        fp = nullptr;
        qDebug() << "AddInotifyMaxUserInstance finished:" << ba;
    } else {
        qWarning() << "AddInotifyMaxUserInstance: popen open failed";
        return -1;
    }
    return instances;
}
