/*
 * Copyright (C) 2025 UBports Foundation
 *
 * 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; version 3.
 *
 * 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 <http://www.gnu.org/licenses/>.
 *
 * Authors: Alfred Neumayer <alfred@ubports.com>
 */

#include "commandrunner.h"

#include <QDebug>
#include <QThread>

CommandRunner::CommandRunner(QObject *parent) :
    QObject(parent)
{
}

int CommandRunner::shell(const QStringList &command, const bool waitForCompletion, QByteArray* output)
{
    QStringList cmd = QStringList{"-c", command.join(" ")};

    QObject::disconnect(&m_process, &QProcess::readyReadStandardOutput, nullptr, nullptr);

    if (!output) {
        QObject::connect(&m_process, &QProcess::readyReadStandardOutput,
                         this, [=]() {
            const QByteArray stdOutContent = m_process.readAllStandardOutput();
            qDebug() << stdOutContent;
            const auto split = QString::fromUtf8(stdOutContent).split("\n", Qt::SkipEmptyParts);
            for (const auto& val : split) {
                Q_EMIT outputReceived(val);
            }
        }, Qt::DirectConnection);
        QObject::connect(&m_process, &QProcess::readyReadStandardError,
                         this, [=]() {
            const QByteArray stdErrContent = m_process.readAllStandardError();
            qDebug() << stdErrContent;
            if (stdErrContent.contains("userpasswd")) {
                Q_EMIT passwordRequested();
            }
        }, Qt::DirectConnection);
    }

    this->m_process.start("bash", cmd, QProcess::ReadWrite);
    this->m_process.waitForStarted();

    if (waitForCompletion) {
        this->m_process.waitForFinished(std::numeric_limits<int>::max());
        if (output) {
            *output = this->m_process.readAllStandardOutput();
        }
        qDebug() << this->m_process.exitCode();
        const int ret = this->m_process.exitCode();
        return ret;
    }
    return -1;
}

int CommandRunner::sudo(const QStringList &command, const bool waitForCompletion, QByteArray* output)
{
    QStringList cmd = QStringList{"-S", "-p", "userpasswd"} + command;
    qDebug() << "running" << cmd.join(" ");

    QObject::disconnect(&m_process, &QProcess::readyReadStandardOutput, nullptr, nullptr);

    if (!output) {
        QObject::connect(&m_process, &QProcess::readyReadStandardOutput,
                         this, [=]() {
            const QByteArray stdOutContent = m_process.readAllStandardOutput();
            qDebug() << stdOutContent;
            const auto split = QString::fromUtf8(stdOutContent).split("\n", Qt::SkipEmptyParts);
            for (const auto& val : split) {
                Q_EMIT outputReceived(val);
            }
        }, Qt::DirectConnection);
        QObject::connect(&m_process, &QProcess::readyReadStandardError,
                         this, [=]() {
            const QByteArray stdErrContent = m_process.readAllStandardError();
            qDebug() << stdErrContent;
            if (stdErrContent.contains("userpasswd")) {
                Q_EMIT passwordRequested();
            }
        }, Qt::DirectConnection);
    }

    m_process.start("sudo", cmd, QProcess::ReadWrite);
    m_process.waitForStarted();

    if (waitForCompletion) {
        m_process.waitForFinished(std::numeric_limits<int>::max());
        if (output) {
            *output = m_process.readAllStandardOutput();
        }
        qDebug() << m_process.exitCode();
        const int ret = m_process.exitCode();
        return ret;
    }
    return -1;
}

bool CommandRunner::sudo(const QStringList &command)
{
    return sudo(command, true, nullptr);
}

void CommandRunner::writeInput(const QString input)
{
    this->m_process.write(input.toUtf8());
    this->m_process.write("\n");
}

bool CommandRunner::validatePassword()
{
    const QStringList trueCommand {
        QStringLiteral("/usr/bin/true")
    };
    return (sudo(trueCommand, true) == 0);
}

void CommandRunner::cancel()
{
    m_process.kill();
    m_process.waitForFinished();
}
