/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/



#include	"xlerror.h"
#include	"xl.h"
#include	"xl_server.h"

XL_SEXP * xl_DefineAgent();

void
init_DefineAgent(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"DefineAgent"),
		get_func_prim(xl_DefineAgent,FO_APPLICATIVE,0,6,6));
}

XL_SEXP *
xl_DefineAgent(XLISP_ENV * env,XL_SEXP * s,XLISP_ENV * ae,XL_SYM_FIELD * sf)
{
XL_SEXP * host;
XL_SEXP * agent, * type;
AGENT * a;
int flags;
XL_SEXP * e,*func;
XLISP_ENV * _e;
	host = get_el(s,1); 
	agent = get_el(s,2);
	type = get_el(s,3);
	e = get_el(s,4);
	func = get_el(s,5);
	switch ( get_type(host) ) {
	case XLT_ERROR:
		return host;
	case XLT_STRING:
		break;
	default:
		goto type_missmatch;
	}
	switch ( get_type(agent) ) {
	case XLT_ERROR:
		return agent;
	case XLT_STRING:
		break;
	default:
		goto type_missmatch;
	}
	switch ( get_type(type) ) {
	case XLT_ERROR:
		return type;
	case XLT_STRING:
		break;
	default:
		goto type_missmatch;
	}
	switch ( get_type(e) ) {
	case XLT_ERROR:
		return e;
	case XLT_NULL:
		_e = 0;
		break;
	case XLT_ENV:
		_e = e->env.data;
		break;
	default:
		goto type_missmatch;
	}
	switch ( get_type(func) ) {
	case XLT_ERROR:
		return func;
	case XLT_NULL:
		func = 0;
		break;
	case XLT_FUNC:
		break;
	default:
		goto type_missmatch;
	}
	flags = AF_PASSWD;
	for ( ; sf ; sf = sf->next ) {
		if ( l_strcmp(sf->name,l_string(std_cm,"passwd")) == 0 ) {
			if ( l_strcmp(sf->data,l_string(std_cm,"required"))
					== 0 )
				flags |= AF_PASSWD;
			else if ( l_strcmp(sf->data,
					l_string(std_cm,"anonymous")) == 0 )
				flags &= ~AF_PASSWD;
		}
		else if ( l_strcmp(sf->name,
				l_string(std_cm,"dircheck")) == 0 ) {
			if ( l_strcmp(sf->data,l_string(std_cm,"on")) == 0 )
				flags |= AF_DIRCHECK;
			else if ( l_strcmp(sf->data,l_string(std_cm,"off"))
						== 0 )
				flags &= ~AF_DIRCHECK;
		}
	}
	insert_agent(
		host->string.data,
		agent->string.data,
		type->string.data,
		flags,
		_e,
		func);
	return 0;
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"SetAgent"),
		0);
}

