/* -*- Mode:C; Tab-width:4 -*- */
/*                                                                       */
/*                                                                       */
/*                      RESTRICTED RIGHTS LEGEND                         */
/*                                                                       */
/* Use, duplication, or disclosure by the Government is subject to       */
/* restrictions as set forth in subdivision (c)(1)(ii) of the Rights in  */
/* Technical Data and Computer Software clause at 252.227-7013.          */
/*                                                                       */
/*                    TEXAS INSTRUMENTS INCORPORATED.                    */
/*                            P.O. BOX 149149                            */
/*                         AUSTIN, TEXAS 78714-9149                      */
/*                              MS 2151                                  */
/*                                                                       */
/*  Copyright (C)   1987,1988,1989,1990 Texas Instruments Incorporated.  */
/*  All rights reserved.                                                 */
/*                                                                       */

/* 3-13-89  BJ  Conditionalized pathnames for AUX.                             */
/* 3-31-89  BJ  Turned the startup information into a resource.                */
/* 4-20-89  BJ  Restored the ability to read a startup file if one is present. */

#include <files.h>  /*  9/6/89 clm - no longer use files_TI.h  */
#include <Ctype.h>
#include <errno.h>
#include <memory.h>   /* 9/6/89 clm - no longer use memory_TI.h  */
#include <strings.h>    /* 9/6/89 clm - no longer use strings_TI.h  */
#include <osutils.h> /* For sysbeep() */
#include <stdio.h>   /* For debug printf's. */
#include "read_startup.h"
#include <resources.h>
#include <utility.h>
#include <micronet-accessors.h>
#include <dialogs.h>
#define READ_STARTUP                  16

StringPtr			lispm_volume_array[maxdisks]; 	/* lispm volumes */
char startupfile[80] ;

startup_tbl			**startup_parms = NULL ;
	
struct size **sizeinfo = NULL;  /* The multiFinder size resource. */

int startup_echo = 0;

/*  read_startup() - Read Configuration File 
		
	Known Keywords: 
		Same as member names of startup_parms, defined in "read_startup.h".
	
		-  Find and process the microExplorer's configuration file.
			It searches all volumes in their natural MAC order,
			looking for the file "startup" in directory "microExp".
		-  Processes the startup file.  File is ascii lines, each line 
			containing "keyword = value". The results are put into a
			startup_parms structure and a pointer to it is returned.
		-  Failure to find or open a file will cause NULL to be returned.
		-  On success, use the structure, startup_parms.
		-  Things known about but not included in a given config file will
			generally be set to the	empty string.  The autoboot flag is an
			exception.
*/ 

/* Convert uppercase alphas chars in str to lowercase */
string_lower(str)
register char *str;
{
	while (*str != 0) {
		if ((isalpha(*str)) && (isupper(*str)))
			*str = tolower(*str);
		++str;
	}
}

find_all_lispm_volumes()
{
	int				i,blks,total,error,volume_count;
  	char  			myvolume[volsize + 1]; 
	char *volname ;
    struct 			HVolumeParam    volbuf;
	union			CInfoPBRec      cbuf;
    char pathname[128] ;

    for (i=0; i < maxdisks; i++)
		lispm_volume_array[i] = NULL ;
	volume_count = 0;
	i = 1;
	while (i <= maxdisks) {
		volbuf.ioVolIndex = i;
		volbuf.ioNamePtr = myvolume;
		volbuf.ioCompletion = NULL;
		if ((error = PBHGetVInfo((HParmBlkPtr)&volbuf, false)) == 0)  {
		    /* clm 9/27/89 - did the cast */
			volname = p2cstr(volbuf.ioNamePtr);
			blks = volbuf.ioVNmAlBlks;
			if (blks < 0) blks = 0X10000 + blks;
			total = blks * volbuf.ioVAlBlkSiz;
			if (total >= ignorevolumesize) {
				strcpy(pathname, volname);
 			    strcat(pathname, AUX_p ? "/users/microexp/" : ":microExp");  
			    cbuf.hfileInfo.ioNamePtr       = c2pstr(pathname);
	    	    cbuf.hfileInfo.ioFDirIndex     = 0; 
       		    if ((error = PBGetCatInfo((CInfoPBPtr)&cbuf, false)) == 0)  {
				          /* clm 9/27/89 - did the cast to CInfoPBPtr */
						  if ((lispm_volume_array[volume_count] = (StringPtr) malloc(strlen(volname) + 1)) == 0) {  
						  /* clm 9/27/89 - cast to (StringPtr) */ 
					  	  PrtErrorMsg(213); /* Mem alloc error-disk, don't get any more volumes */
						  return(-1);
						}
					  strcpy(lispm_volume_array[volume_count], volname);
					  volume_count++;
				}
			}
   		}
		i++;
	}

}


pascal void
write_startup()
{

	if(startupfile[0] == '\0')
	  {
		  ChangedResource((Handle)startup_parms);  /* clm 9/27/89 - cast to (Handle) for both instructions  */
		  WriteResource((Handle)startup_parms);
	  }
	else
	  {
		  FILE *fp ;
		  
		  fp = fopen(startupfile, "w") ;
		  if (fp == NULL)
			{
				printw("Can't write startup file %s\n", startupfile) ;
				return ;
			}
		  fprintf(fp, "mcrname = %s\n", &((*startup_parms)->mcrname[0])) ;
		  fprintf(fp, "mcrvolume = %s\n", &((*startup_parms)->mcrvolume[0])) ;
		  fprintf(fp, "loadname = %s\n", &((*startup_parms)->loadname[0])) ;
		  fprintf(fp, "loadvolume = %s\n", &((*startup_parms)->loadvolume[0])) ;
		  fprintf(fp, "hostname = %s\n", &((*startup_parms)->hostname[0])) ;
		  fprintf(fp, "forslot = %d\n", ((*startup_parms)->forslot)) ;
		  fprintf(fp, "defaultdevice = %s\n", &((*startup_parms)->defaultdevice[0])) ;
/*		  fprintf(fp, "windowheap = %x\n", ((*startup_parms)->windowBitArraySize)) ; */
		  fprintf(fp, "mischeap = %x\n", ((*startup_parms)->miscHeapSize)) ;
		  fclose(fp) ;	
	  }
}

scan_file(fptr)
FILE	*fptr;
{
	int	 args = 0;
    char key[128] ;
	char val[128] ;

#ifdef DEBUG
	printf("Scan File\n");
#endif

	while (args >= 0)
	  {
		  if ((args = fscanf(fptr,"%s%*s%s",key,val)) > 0)
			{
				string_lower(key);
				
				if (!(strncmp(key,"mcrname",7)))
				  strncpy(&((*startup_parms)->mcrname[0]), val, 32);
				
				if (!(strncmp(key,"mcrvolume",9)))
				  strncpy(&((*startup_parms)->mcrvolume[0]), val, 32);
				
				if (!(strncmp(key,"loadname",8)))
				  strncpy(&((*startup_parms)->loadname[0]), val, 32);
				
				if (!(strncmp(key,"loadvolume",10)))
				  strncpy(&((*startup_parms)->loadvolume[0]), val, 32);
				
				if (!(strncmp(key,"hostname",8)))
				  strncpy(&((*startup_parms)->hostname[0]), val, 16);
				
				if (!(strncmp(key,"forslot",8)))
				  sscanf(val,"%d",&((*startup_parms)->forslot));
				
				if (!(strncmp(key,"defaultdevice",8)))
				  strncpy(&((*startup_parms)->defaultdevice[0]),val,32);

				if (!(strncmp(key,"windowheap",10)))
				  sscanf(val,"%x",&((*startup_parms)->windowBitArraySize));

				if (!(strncmp(key,"mischeap",10)))
				  sscanf(val,"%x",&((*startup_parms)->miscHeapSize));
		
			}
	  }
	  
#ifdef DEBUG
	printf("Forslot = 0x%x\n", ((*startup_parms)->forslot));
	printf("Default Device = %s\n",&((*startup_parms)->defaultdevice[0]));
	printf("HOST name = %s\n",&((*startup_parms)->hostname[0]));
	printf("mcr=%s, load=%s\n", &((*startup_parms)->mcrname[0]), &((*startup_parms)->loadname[0]));
#endif
}

void
read_size_resource()
{
	/* Get the handle to the multiFinder size resource. */
	if(!sizeinfo)
	  if(!(sizeinfo = (struct size **) GetResource('SIZE', 0))) /* clm 9/27/89 - cast it, but a handle should have been defined.  */
		{
			/* If we read -1 then copy it to 0 and add it. */
			if(sizeinfo = (struct size **) GetResource('SIZE', -1))  /* clm 9/27/89 - cast it */
			  {
#ifdef TRASH
  		          struct size **newsizeinfo = sizeinfo;
				  short error = HandToHand(&newsizeinfo);
				  if(error) debugstr("Error copying size resource.");
				  addresource(newsizeinfo, 'SIZE', 0, "");
				  SetResAttrs(newsizeinfo, GetResAttrs(sizeinfo));
				  /* Don't worry about writing it unless we need to change it. */
				  
				  sizeinfo = newsizeinfo;
#endif
				  
			  }
			else
			  debugstr("Size resource not found.");	
		}
}

void
write_size_resource()
{
    /* Make the size break on an even k. */
	(*sizeinfo)->preferredMemorySize += (*sizeinfo)->preferredMemorySize % 1024;
	printf("Changing application size to %x\n", (*sizeinfo)->preferredMemorySize);
	ChangedResource((Handle)sizeinfo);   /* clm 9/27/89 - cast both of the following */
	WriteResource((Handle)sizeinfo);
	paramtext("Changing the microExplorer's application size.","","You must reboot for this change to take affect.","");
	NoteAlert (260,0);
}

pascal startup_tbl	**
read_startup()
{
	FILE	*fptr;
	int	i,error;
	char 	*startup_path	=	AUX_p ? "/users/microexp/startup" : ":microExp:startup";      /*ab 3/8/88 */

	read_size_resource();
		
	/* Don't re-read it. */
	if (startup_parms)
		return(startup_parms) ;
		
 	/* Other applications get their startup info from the driver. */
	if(!in_driver_p)
	  {
		  Ptr parms[5];
		  unsigned short error;

		  if(error = r_ioctl(DriverData->refnum, READ_STARTUP, &parms[0]))
			debugstr("Error reading startup info.");

		  return startup_parms = (startup_tbl **) parms[0];		/* clm 9/27/89 - cast */ 
	  }

	/* Get the resource first. This will give us an initialized table. */
	startup_parms = (startup_tbl **) GetResource('STRT', 0);   /* clm 9/27/89 - cast */
	if(!startup_parms) debugstr("Startup information not found.");


	find_all_lispm_volumes();		/* 	This is done just once per lispm boot.
										The result is in lispm_volume_array. */
	for(i=0; i<maxdisks; i++)
	  {
		  /*	Now look for the startup file and open it.	*/
		  if (lispm_volume_array[i] == NULL)
	          break;
			 
		  strcpy(startupfile, lispm_volume_array[i]);
	      strcat(startupfile, startup_path);
		  fptr = fopen(startupfile,"r");
		  
#ifdef DEBUG
		  printf("trying '%s'\n", startupfile) ;
#endif

		  if (fptr != NULL)
			{	
				/* open worked */
				
				if (startup_echo)
				  printf("Reading Startup File %s\n", startupfile);
				
				scan_file(fptr);
				error = fclose(fptr);
				break;
			}
		  startupfile[0] = '\0' ;			/* no dice */
	  }
	  
	
	if(startupfile[0] == '\0')
	  printf("Reading startup parms from application resource.\n");

#ifdef TRASH
	/* Check to see if the size resource is up to date. */
	if(((*startup_parms)->windowBitArraySize + (*startup_parms)->miscHeapSize) +
	    (((*startup_parms)->windowBitArraySize + (*startup_parms)->miscHeapSize) % 1024) != 
	   (*sizeinfo)->preferredMemorySize)
	  {
		  printf("Changing the microExplorer applications size from %d to %d.\n",
				 (*sizeinfo)->preferredMemorySize,
				 ((*startup_parms)->windowBitArraySize + (*startup_parms)->miscHeapSize));
		  
		  (*sizeinfo)->preferredMemorySize = (*startup_parms)->windowBitArraySize + (*startup_parms)->miscHeapSize;
		  write_size_resource();
		  exit(-1);
	  }
#endif
	return startup_parms;
}
	
pascal char *
startup_defaultdevice(table)
	startup_tbl	**table;
{
    return &(*table)->defaultdevice[0];
}

pascal char *
startup_hostname(table)
	startup_tbl	**table;
{
    return &(*table)->hostname[0];
}

pascal char *
startup_loadvolume(table)
	startup_tbl	**table;
{
    return &(*table)->loadvolume[0];
}

pascal char *
startup_loadname(table)
	startup_tbl	**table;
{
    return &(*table)->loadname[0];
}

pascal char *
startup_mcrname(table)
	startup_tbl	**table;
{
    return &(*table)->mcrname[0];
}

pascal char *
startup_mcrvolume(table)
	startup_tbl	**table;
{
    return &(*table)->mcrvolume[0];
}

pascal int
startup_windowBitArraySize(table)
	startup_tbl  **table;
{
	return (*table)->windowBitArraySize;
}

pascal unsigned char
startup_forslot(table)
	startup_tbl **table;
{
	return (*table)->forslot;
}


