/***************************** 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 string& cmd, IconObject* o) :
    object_(o),
    file_(0),
    cmd_(cmd)
{
}

ShellTask::~ShellTask()
{
}

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 << endl;
        Request r;
        failure(r);
        return;
    }
    Input::start(file_);
}

void ShellTask::ready(const char* line)
{
    Log::error(object_) << line << 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_ << "'." << endl;
        Log::error(object_) << "Exit code: " << n << endl;
        Request r;
        failure(r);
    }
    else {
        Request r;
        success(r);
    }
    file_ = 0;
    Input::stop();
}

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