/* configuration file format:
   each line beginning with a # is a comment and is ignored
   each empty line (containing only a \n) is ignored
   all lines longer than LINELEN-2 characters are ignored
   all lines must not begin with a space or tab character
   all other lines must conform to this format:
   "hostname program arg0 arg1 ... arg8"
   arg0 should be the program name
   there are no more than MAXLINES-1 non-empty, non-comment lines allowed
*/

#include <stdio.h>
#include <fcntl.h>
#include <syslog.h>
#include <string.h>

#define CONFFILE "/etc/tsh.conf"
#define LINELEN 256
#define MAXLINES 256
#define MAXTOKEN 11 /* hostname + 10 arguments */

char ***readconfig(void)
{
     char tmp[LINELEN], *ptr;
     char ***config;
     int j=0, cnt=0, scnt=0, ign=0;
     FILE *cf;

     if((config=calloc(MAXLINES+1, sizeof(char**))) == NULL) {
	  perror("failed to allocate memory");
	  exit(1);
     }
     tmp[LINELEN-1]='\0';

     if((cf=fopen(CONFFILE, "r")) == NULL) {
	  perror("cannott open configuration file");
	  exit(1);
     }
     
     while(ptr=fgets(tmp, LINELEN, cf)) {
	  cnt++;
	  if(strlen(ptr)==LINELEN-1) {
	       if(!ign) syslog(LOG_WARNING|LOG_AUTH, "line %d too long in configuration file (ignored)", cnt);
	       ign=1;
	       continue;
	  }
	  if(ign) {
	       ign=0;
	       continue; /* rest of overlong line */
	  }
	  if(*ptr=='#')
	       continue; /* comment */
	  if(*ptr=='\n')
	       continue; /* empty */

	  tmp[strlen(ptr)-1]=0;
	  config[scnt]=calloc(MAXTOKEN+1, sizeof(char*));
	  config[scnt][0]=strtok(strdup(tmp), " \t");
	  for(j=1; j!=MAXTOKEN; j++)
	       if((config[scnt][j]=strtok(NULL, " \t")) == NULL)
		    break;
	  scnt++;
     }
     fclose(cf);
     return(config);
}

int main(argc, argv)
     int argc;
     char **argv;
{
     char host[LINELEN], ***ptr;
     char ***config=readconfig();

     printf("host? ");
     fgets(host, LINELEN, stdin);
     host[strlen(host)-1]=0;
     for(ptr=config; *ptr!=NULL; ptr++) {
	  if(strncmp((*ptr)[0],host,LINELEN)==0) {
	       execvp((*ptr)[1],(*ptr)+2);
	       perror("exec() failed");
	       exit(1);
	  }
     }
     fprintf(stderr,"illegal host\n");
}
