/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <Metview.h>
#include <MvShellTask.h>


MvShellTask::MvShellTask(MvClient* c, const char* s, const char* taskName) :
    MvTask(c, taskName),
    Command(s)
{
}


boolean MvShellTask::_inputCB(FILE* f, void* data)
{
    auto* task = (MvShellTask*)data;
    char line[1024];
    if (fgets(line, sizeof(line), f)) {
        task->input(line);
        return true;
    }
    else {
        task->setError(pclose(f));
        task->done();
        return false;
    }
}

void MvShellTask::run()
{
    char buf[1024];
    sprintf(buf, "%s 2>&1 < /dev/null", (const char*)Command);

    // Should use MvApp...

    FILE* f = popen(buf, "r");
    if (!f) {
        marslog(LOG_EROR, "Command failed: %s", buf);
        setError(-1);
        done();
    }
    add_input_callback(MvApplication::getService(), f, _inputCB, this);
}

void MvShellTask::input(char* line)
{
    progress(line);
}
