/**********************************************************************
 
	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	<stdio.h>
#include	<fcntl.h>


char filename[1000];

int
search_str(char * filename,char * data)
{
FILE * fd;
char buf[4000];
char * p;
	fd = fopen(filename,"r+");
	if ( fd == 0 )
		return 0;
	for ( ; ; ) {
		if ( fgets(buf,4000,fd) == 0 )
			break;
		for ( p = buf ; *p ; p ++ )
			if ( memcmp(data,p,strlen(data)) == 0 ) {
				fclose(fd);
				return 1;
			}
	}
	return 2;
}

int
install_mime_etc()
{
FILE * fd;
int header;
	sprintf(filename,"%s/.mime.types",getenv("HOME"));

	switch ( search_str(filename,"text/gb") ) {
	case 0:
		header = 1;
		break;
	case 1:
		goto mailcap;
	case 2:
		header = 0;
		break;
	}
	fd = fopen(filename,"a+");
	if ( fd == 0 ) {
		perror(".mime.types");
		exit(1);
	}
	if ( header ) {
		fprintf(fd,
	"#--Netscape Communications Corporation MIME Information\n");
		fprintf(fd,
	"#Do not delete the above line. It is used to identify the file type.\n");
		fprintf(fd,"#\n");
	}
	fprintf(fd,"# mime types added by COSMOS GLOBALBASE VIEWER\n");
	fprintf(fd,"type=text/gb \\\n");
	fprintf(fd,"desc=\"GLOBALBASE protocol\" \\\n");
	fprintf(fd,"exts=\"gb\" \\\n");
	fclose(fd);

mailcap:
	sprintf(filename,"%s/.mailcap",getenv("HOME"));

	switch ( search_str(filename,"text/gb") ) {
	case 0:
		header = 1;
		break;
	case 1:
		exit(1);
	case 2:
		header = 0;
		break;
	}
	fd = fopen(filename,"a+");
	if ( fd == 0 ) {
		perror(".mailcap");
		exit(1);
	}
	if ( header ) {
		fprintf(fd,
	"#--Netscape Communications Corporation MIME Information\n");
		fprintf(fd,
	"#Do not delete the above line. It is used to identify the file type.\n");
		fprintf(fd,"#\n");
	}
	fprintf(fd,"# mailcap entry added by COSMOS GLOBALBASE VIEWER\n");
	fprintf(fd,"text/gb;cosmos i %%s\n");
	fclose(fd);

	return 0;
}

int
main(int argc,char ** argv)
{

	if ( argc < 2 ) {
		fprintf(stderr,"too few arguments\n");
		fprintf(stderr,"option(-all/-app/-env) is required\n");
		fprintf(stderr,"you can get more information at\n");
		fprintf(stderr,
	"http://www.nichibun.ac.jp/~joshua/globalbase/install.unix.html\n");
		exit(1);
	}

	if ( strcmp(argv[1],"-all") == 0 ||
			strcmp(argv[1],"-app") == 0 ) {
		grue(argv[0]);
		system("cp installer.t bin/cosmos_installer.t");
	}

	if ( strcmp(argv[1],"-all") == 0 ||
			strcmp(argv[1],"-env") == 0 )
		install_mime_etc();

	exit(0);
}
