/**********************************************************************
 
	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	"memory_debug.h"
#include	"acrp.h"
#include	"gbmp.h"

void
_trigger_around(int ses,L_CHAR * url,int flags)
{
URL u;
int p;
int local_ip;
L_CHAR * path;
	p = get_my_port();
	local_ip = get_xllisp_site_ip().d.v4;
	get_url2(&u,url);
	if ( u.server == 0 && u.port == 0 ) {
		u.port = p;
	}
	path = get_url_filepath(&u);
	if ( cmp_site(u.server,0,u.port,
			0,local_ip,p) == 0 ) {
		if ( flags & TAF_LOCAL )
			insert_tick_que(0,path,TQT_CRD,TQL_ACRP);
	}
	else {

		if ( flags & TAF_REMOTE ) {
/*
ss_printf("trigger remote %ls\n",
path);
*/
			gc_push(0,0,"remote_fetch");

			remote_session(
				gblisp_top_env0,
				ses,
				&u,
				l_string(std_cm,"gbstd"),
				l_string(std_cm,"user"),
				l_string(std_cm,"Get"),
				List(List(n_get_symbol("MPTrigger"),
					get_string(path),
					-1),
					-1),
				0,0,1,0);
	
			gc_pop(0,0);

		}
	}
	free_url(&u);
	d_f_ree(path);
}

void
_purge(int ses,L_CHAR * url,L_CHAR * purge_path)
{
URL u;
int p;
int local_ip;
L_CHAR * path;
URL uu;

//ss_printf("_purge purge_path = %ls\n",purge_path);

	get_url2(&uu,purge_path);
	if ( uu.proto == 0 ) {
		uu.proto = nl_copy_str(std_cm,"xlp");
	}
	if ( uu.server == 0 ) {
		uu.server = ll_copy_str(get_xllisp_site());
	}
	if ( uu.port == 0 )
		uu.port = get_my_port();
	purge_path = ll_copy_str(get_url_str2(&uu));
	free_url(&uu);

//ss_printf("_purge %ls => %ls\n",url,purge_path);

	p = get_my_port();
	local_ip = get_xllisp_site_ip().d.v4;
	get_url2(&u,url);
	if ( u.server == 0 && u.port == 0 ) {
		u.port = p;
	}
	path = get_url_filepath(&u);
	if ( cmp_site(u.server,0,u.port,
			0,local_ip,p) ) {

		gc_push(0,0,"remote_fetch");

		remote_session(
			gblisp_top_env0,
			ses,
			&u,
			l_string(std_cm,"gbstd"),
			l_string(std_cm,"user"),
			l_string(std_cm,"Get"),
			List(List(n_get_symbol("MPPurge"),
				get_string(purge_path),
				-1),
				-1),
			0,0,1,0);

		gc_pop(0,0);
	}
	free_url(&u);
	d_f_ree(path);
	d_f_ree(purge_path);
}

void
trigger_around(int ses,L_CHAR * my_path,AROUND_LIST * al,int flags)
{
	for ( ; al ; al = al->next ) {
		if ( flags & TAF_REMOTE )
			_purge(ses,al->crd,my_path);
		_trigger_around(ses,al->crd,flags);
	}
}

