/***************************** 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 <inc_iostream.h>

#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 );
	cout << "\n command: " << buf << endl;

	FILE *f = popen(buf,"r");;
	if(f == 0)
	{
		setError(1,"call to Ecfs failed");
		return;
	}
	cout << " command started ok" << endl;

	while(fgets(buf,sizeof(buf),f))
	{
		if(*buf) buf[strlen(buf)-1] = 0;
		marslog(LOG_INFO,"%s",buf);	
	}

	int e;
	if((e = pclose(f)))
	{
		marslog( LOG_EROR, "%s", ecfs_cmd );	
		setError(1,"Ecfs call returned error code %d",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();
}
