/***************************** 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 "ShellTask.h"
#include "IconObject.h"
#include "Log.h"
#include "Request.h"


//=================================================================

ShellTask::ShellTask(const std::string& cmd, IconObject* o) :
    object_(o),
    file_(nullptr),
    cmd_(cmd)
{
}

ShellTask::~ShellTask() = default;

void ShellTask::start()
{
    Path path = object_->pathForShellTask();
    // Here we are using a specialised version of the path.
    // To allow the visualisation of the PS files coming from
    // the MagML tools.
    const char* p = path.str().c_str();
    char buf[1024];
    sprintf(buf, cmd_.c_str(), p, p, p, p, p, p);
    file_ = popen(buf, "r");
    if (!file_) {
        Log::error(object_) << buf << Log::syserr << std::endl;
        Request r;
        failure(r);
        return;
    }
    Input::start(file_);
}

void ShellTask::ready(const char* line)
{
    Log::error(object_) << line << std::endl;
}

void ShellTask::done(FILE* /*f*/)
{
    TaskH save = this;  // Protect this so it can cleanup
    // everything before being destryed

    int n = 0;
    if ((n = pclose(file_))) {
        Log::error(object_) << "Problems running: '" << cmd_ << "'." << std::endl;
        Log::error(object_) << "Exit code: " << n << std::endl;
        Request r;
        failure(r);
    }
    else {
        Request r;
        success(r);
    }
    file_ = nullptr;
    Input::stop();
}

void ShellTask::print(std::ostream& s) const
{
    s << "ShellTask[" << cmd_ << "]";
}
