/***************************** 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 *************************************/

// Modified from Baudouin's 'Ecfile.cc' by vk/961115

#include <Metview.h>

//______________________________________________________

class Ecfs : public MvService
{
public:
    Ecfs() :
        MvService("ECFS") {}
    void serve(MvRequest&, MvRequest&);
};
//______________________________________________________

void Ecfs::serve(MvRequest& in, MvRequest& out)
{
    const char* path = in("FILE_NAME");
    const char* domain = in("ECFS_DOMAIN");
    char buf[1024];
    char ecfs_cmd[1024];
    char* tmp = marstmp();

    in.print();

    sprintf(ecfs_cmd, "ecp -o %s%s %s", domain, path, tmp);

    // sprintf(buf,"csh -exec \'Ecp ec:%s %s 2>&1\'",path,tmp);
    // sprintf(buf,"csh -exec \'Ecp -o ec:%s %s\'",path,tmp);
    sprintf(buf, "ksh -c \' . $HOME/.kshrc ; set -e ; %s\'", ecfs_cmd);
    sendProgress("Ecfs-> command: %s", buf);

    FILE* f = popen(buf, "r");
    if (f == nullptr) {
        setError(1, "Ecfs-> call to Ecfs failed");
        return;
    }

    while (fgets(buf, sizeof(buf), f)) {
        if (*buf)
            buf[strlen(buf) - 1] = 0;

        sendProgress("Ecfs-> %s", buf);
    }

    int e;
    if ((e = pclose(f))) {
        setError(1, "Ecfs-> Call (%s) returned error code %d", ecfs_cmd, e);
        return;
    }

    MvRequest grib = guess_class(tmp);
    grib("PATH") = tmp;
    grib("TEMPORARY") = 1;
    out = grib;
}
//______________________________________________________

int main(int argc, char** argv)
{
    MvApplication theApp(argc, argv);
    Ecfs myEcfs;
    theApp.run();
}
