/**********************************************************************
 
	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	<netdb.h>
#include	"task.h"
#include	"memory_debug.h"
#include	"netutils.h"


extern SEM netutils_lock;

void
get_localhostname(char * buf)
{
static char * ret_buf;
struct hostent * hp;
char ** q;
int len;
char * dom;

	lock_task(netutils_lock); 
	if ( ret_buf ) {
		unlock_task(netutils_lock,"get_localhostname");
		strcpy(buf,ret_buf);
		return;
	}
	sethostent_rr(0); 
	for ( ; ; ) {
		hp = gethostent_rr();
		if ( hp == 0 ) {
			endhostent_rr();
			strcpy(buf,"localhost");
			break;
		}
		q = hp->h_aliases;
		for ( ; *q ; q ++ ) {
			if ( strcmp((*q),"loghost")
					== 0 )
				break;
		}
		if ( *q == 0 )
			continue;
		strcpy(buf,hp->h_name);
		len = strlen(buf);
		q = hp->h_aliases;
		dom = get_localdomainname();
		for ( ; *q ; q ++ ) {
			if ( strcmp((*q),"loghost") == 0 )
				continue;
			if ( dom ) {
				if ( strlen(*q) > len )
					continue;
			}
			else {
				if ( strlen(*q) <= len )
					continue;
			}
			strcpy(buf,*q);
			len = strlen(*q);
		}
		endhostent_rr();
		if ( dom ) {
		char * p;
			p = buf + strlen(buf);
			*p++ = '.';
			strcpy(p,dom);
		}
		break;
	}
	ret_buf = d_alloc(strlen(buf)+1,1);
	strcpy(ret_buf,buf);
	unlock_task(netutils_lock,"get_localhostname");
}
