#include <QtGlobal>
#include <QCoreApplication>
#include <QByteArray>

#include <QProcess>
#include <QCommandLineParser>
#include <QCommandLineOption>
#include <QStandardPaths>
#include <QSettings>
#include <QDir>
#include <QDebug>

#include "message_handler.h"
#include "utils_internal.h"
#include "opkg_command.h"

int main(int argc, char **argv) {

    QByteArray const value = qgetenv("LC_ALL");
    if (value.isEmpty() || value != "C") {
        qputenv("LC_ALL", "C");
    }

    openlog("ATB-UPDATE-OPKG", LOG_PERROR | LOG_PID | LOG_CONS, LOG_USER);

    QCoreApplication a(argc, argv);
    QCoreApplication::setApplicationName("ATBUpdateOpkg");
    QCoreApplication::setApplicationVersion(APP_VERSION);

    if (!messageHandlerInstalled()) { // change internal qt-QDebug-handling
        atbInstallMessageHandler(nullptr);
        //atbInstallMessageHandler(atbDebugOutput);
        setDebugLevel(LOG_NOTICE);
    }

#if 0
    QString s = "<OPKG>\n\naaa<OPKG>bbb<OPKG>ccc<OPKG>\n";
    QString m_standardOutput{};
    if (!s.isEmpty()) {
        m_standardOutput += s.replace(QChar('\n'), "");
        qCritical() << m_standardOutput;

        int startIndex, endIndex{};
        while (((startIndex = m_standardOutput.indexOf("<OPKG>")) == 0) &&
               ((endIndex = m_standardOutput.indexOf("<OPKG>", 1)) != -1)) {
                QString str = m_standardOutput.mid(0, endIndex);
                qCritical() << "str" << str << str.mid(6);
                m_standardOutput = m_standardOutput.mid(endIndex);
                // qCritical() << "m" << m_standardOutput;
        }
        qCritical() << "m" << m_standardOutput;
    }

    return 0;
#endif

    QCommandLineParser parser;
    QCommandLineOption noactionOption("noaction");
    QCommandLineOption verboseOption("verbose");
    parser.addOption(noactionOption);
    parser.addOption(verboseOption);
    parser.process(a);

    bool noaction = parser.isSet(noactionOption);
    OpkgCommand opkgCmd(noaction);


    return 0;
}