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

#include	<sys/param.h>
#include	<unistd.h>
#include	"utils.h"
#include	"limits.h"

char *http_client = 0;

unsigned int
call_system(int fd,char * str,char * search)
{
int p[2];
int id;
char * buf;
char * ptr;
int er,c,len;
unsigned int ret;
	pipe(p);
	id = fork();
	if ( id == 0 ) {
		close(fd);
		dup(p[1]);
		close(p[0]);
		for ( id = 3 ; id <= OPEN_MAX ; id ++ )
			close(id);
		system(str);
		exit(0);
	}
	close(p[1]);
	buf = d_alloc(100,123);
	c = 0;
	for ( ; ; c += er ) {
		buf = d_re_alloc(buf,c + 100);
		er = read(p[0],&buf[c],100);
		if ( er <= 0 )
			break;
	}
	close(p[0]);
	if ( search ) {
		len = strlen(search);
		for ( ptr = buf ; c ; c -- , ptr ++ )
			if ( memcmp(ptr,search,len) == 0 ) {
				d_f_ree(buf);
				return -1;
			}
		d_f_ree(buf);
		return 0;
	}
	d_f_ree(buf);
	if ( er <= 0 )
		return 0;
	return -1;
}

void
_http_system(
	char * browser,
	char * hostname,
	int port,
	char * page)
{
char * buf;
int id;
int i;
	buf = d_alloc(1000,144);
	id = fork();
	if ( id == 0 ) {
		for ( i = 3 ; i <= OPEN_MAX ; i ++  )
			close(i);
		if ( page == 0 ) {
			sprintf(buf,"%s http://%s:%i/ &",
				browser,
				hostname,
				port);
		}
		else {
			sprintf(buf,"%s %s &",browser,page);
		}
		system(buf);
		exit(0);
	}
	d_f_ree(buf);
}


void
_http_netscape(
	char * hostname,
	int port,
	char * page)
{
char * buf;
int ret1,ret2;
extern char http_str[];

	buf = d_alloc(1000,1445);
	sprintf(buf,
		http_str,
		getenv("USER"));
	ret1 = call_system(1,buf,"netscape");
	if ( ret1 == 0 ) {
		sleep_sec(1);
		ret2 = call_system(1,buf,"netscape");
	}
	else	ret2 = 0;
	if ( ret1 || ret2 ) {
		if ( page )
			sprintf(buf,"netscape -remote 'openURL(%s)'",
				page);
		else	sprintf(buf,
			"netscape -remote 'openURL(http://%s:%i/)'",
				hostname,port);
		ret1 = call_system(2,buf,0);
		d_f_ree(buf);
		if ( ret1 == 0 )
			return;
	}
	else	_http_system("netscape",hostname,port,page);
}

void
http_system(
	    char * hostname,
	    int port,
	    char * page)
{
	if ( http_client == 0 || strcmp(http_client,"netscape") == 0 )
		return	_http_netscape(hostname,port,page);
	return _http_system(http_client,hostname,port,page);
}
