/*
 * © Copyright 1996-2012 ECMWF.
 * 
 * This software is licensed under the terms of the Apache Licence Version 2.0
 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. 
 * In applying this licence, ECMWF does not waive the privileges and immunities 
 * granted to it by virtue of its status as an intergovernmental organisation nor
 * does it submit to any jurisdiction.
 */

#include <string.h>
#include "mars.h"
#include "ecaccess.h"

typedef struct ecaccessdata 
{
	char    *echost;
	char    *eccommand;
	char    *ecaccesshome;
	int     eccertport;
	char    *ecservice;

} ecaccessdata;

static option ecaccessopts[] = {
	{"echost","ECHOST",NULL,"ecaccess.ecmwf.int",t_str,
	sizeof(char*),OFFSET(ecaccessdata,echost)},
	{"eccertport","ECCERTPORT",NULL,"443",t_int,
	sizeof(int),OFFSET(ecaccessdata,eccertport)},
	{"ecaccesshome","ECACCESS_HOME",NULL,".",t_str,
	sizeof(char*),OFFSET(ecaccessdata,ecaccesshome)},
	{"ectool","ECCOMMAND",NULL,"client/tools/eccert",t_str,
	sizeof(char*),OFFSET(ecaccessdata,eccommand)},
	{"ecservice","EC_MARS_SERVICE",NULL,"ecmars",t_str,
	sizeof(char*),OFFSET(ecaccessdata,ecservice)},
};

static ecaccessdata setup;

err ecaccess_connect(char* host, int* port, char* uid)
{
	int perr = 0;
    char buf[BUFSIZ];
	char cmd[10240];
    FILE *file;
	char *p,*q;

	/* call get_options */
	get_options("mars","ecaccess",&setup,NUMBER(ecaccessopts),ecaccessopts);

	marslog(LOG_DBUG,"ecaccess_connect new version"); 

    sprintf(cmd,"%s/%s -echost %s -ecport %d -tunnel %s",
			setup.ecaccesshome,
			setup.eccommand,
			setup.echost,
			setup.eccertport,
			setup.ecservice
			);

	/* printf("%s\n",cmd); */

	if ((file = popen(cmd, "r")) == NULL)
	{
		marslog(LOG_EROR|LOG_PERR,"Cannot run %s",cmd);
		return -1;
	}

	memset(buf,0,sizeof(buf));
	fgets(buf, BUFSIZ - 1, file); 
	if(strlen(buf)) buf[strlen(buf)-1] = 0;

	if( (perr = pclose(file)) != 0)
	{
		marslog(LOG_EROR,"pclose(%s) returns %d.",cmd,perr);
		return -1;
	}

	/* parse the received string */
	p = buf;
	q = p;

	host[0] = uid[0] = 0; *port = 0;

	while(*p)
	{
		switch(*p)
		{
			case '@':
				*p = 0;
				strcpy(uid,q);
				q = p+1;
				*p = '@';
				break;

			case ':':
				*p  = 0;
				strcpy(host,q);
				*port = atoi(p+1);
				*p = ':';
				break;
		}
		p++;
	}

	if(!host[0] || !uid[0] || !*port)
	{
		marslog(LOG_EROR,"Cannot parse [%s] output of %s",buf,cmd);
		return -1;
	}

    return 0;	
}
