/*************************************************************************
 *    parse the addgame command, and store in a database for later lookup
 *************************************************************************/
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "lafe.h"


struct game *game=NULL;
int games=0;


/* extract the next argument from an addgame commandline */
static char *token(char **str) {
  char *t=NULL;
  int i;

  while (**str && isspace(**str)) (*str)++;

  if (! **str) return NULL;
  
  if (**str=='"') {
    (*str)++;
    for (i=0;(*str)[i]!='"' && (*str)[i];i++) ;
  } else {
    for (i=0;!isspace( (*str)[i] ) && (*str)[i];i++) ;
  }
  t = malloc(i+1);
  strncpy(t,*str,i);
  t[i]=0;
  (*str) += i;
  if (**str) (*str)++;
  return t;
}


void addgame(char *arg) {

  if (!game) {
    game=malloc(sizeof(*game));
  } else {
    game = realloc(game,(games+1)*sizeof(*game));
  }

  memset(game+games,0,sizeof(*game));

  game[games].name = token(&arg);
  if (game[games].name) {
    game[games].country = token(&arg);
    game[games].password = token(&arg);
    game[games].host = token(&arg);
    game[games].port = token(&arg);
    game[games].directory = expand_tilde(token(&arg));
    game[games].logfile = expand_tilde(token(&arg));
    if (game[games].country && game[games].password &&
	game[games].host && game[games].port) {
      games++;
    } else {
      printf("addgame requires country password host and port parameters\n");
    }
  } else {
    int i;
    for (i=0;i<games;i++) {
      printf("%s  %s/%s  %s/%s",game[i].name,game[i].country,
	     game[i].password,game[i].host,game[i].port);
      if (game[i].directory) printf(" %s",game[i].directory);
      else printf(" .");
      if (game[i].logfile) printf(" %s",game[i].logfile);
      else printf(" /dev/null");
      printf("\n");
    }
  }
}

int lookup_game(char *name) {
  int i;
  for (i=0;i<games;i++) {
    if (!strcmp(name,game[i].name)) return i;
  }
  return -1;
}
