/* dosconfig.c
 *    Robert Sanders, gt8134b@prism.gatech.edu
 *    for the Linux DOS emulator version 0.49
 *
 * just a piece of silly rubbish to pour the Makefile command-line define
 * strings into config.h.  I should do this in perl, but since I know
 * everyone who is compiling dosemu has a C compiler, a C program better
 * serves the lowest common denominator.
 *
 * this makes "make depend" a little easier, and the command line a little
 * prettier.  Some of the defines should be runtime-specifiable in a real
 * config file (.dosrc), and some are silly (i.e. the mouse stuff, still
 * unimplemented)
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <sys/utsname.h>
#ifdef __NetBSD__
#include <sys/param.h>
#endif

#define DEF_FORMAT   "#define    %-15s %-15s\n"
#define STR_FORMAT   "#define    %-15s \"%-15s\"\n"

int defs, lone_lvalues;

void
head(void)
{
  printf("/* config.h, DOS emulator configuration file, Robert Sanders,\n");
  printf(" * gt8134b@prism.gatech.edu, generated by dosconfig.c\n");
  printf(" * \n * DO NOT ALTER! \"make config\" will erase your changes!\n");
  printf(" */\n\n#ifndef CONFIG_H\n#define CONFIG_H 1\n\n");
}

void
foot(void)
{
  printf("\n#endif /* config.h */\n\n/* total defines: %3d\n", defs);
  printf(" * end of configuration information\n */\n");
}

void
do_arg(int indx, char *arg)
{
  char *lvalue, *rvalue;

  if (strncmp(arg, "-D", 2)) {
    fprintf(stderr, "not a define: %s\n", arg);
    return;
  }

  /* separate the define of the form -Dlvalue=rvalue into lvalue and rvalue */
  lvalue = strtok(arg + 2, "=");
  rvalue = strtok(NULL, "=");

  defs++;
  if (!rvalue)
    lone_lvalues++;

  printf(DEF_FORMAT, lvalue, rvalue ? rvalue : "");
}

void
host_and_time(void)
{
  time_t postepoch;
  struct utsname uts;
  char localbuf[1000], *ctimestr;
  char host[MAXHOSTNAMELEN + 1];

  uname(&uts);
  gethostname(host, MAXHOSTNAMELEN + 1);
  sprintf(localbuf, "\"%s, %s %s %s\"",
	  host, uts.sysname, uts.release, uts.version);

  printf(DEF_FORMAT, "CONFIG_HOST", localbuf);

  time(&postepoch);
  ctimestr = ctime(&postepoch);
  ctimestr[strlen(ctimestr) - 1] = 0;	/* cut off return char at end of str */
  printf(STR_FORMAT, "CONFIG_TIME", ctimestr);

  /* mark our 2 defines */
  defs += 2;
}

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

  head();
  host_and_time();

  /* process every argument */
  for (indx = 1; indx < argc; indx++)
    do_arg(indx, argv[indx]);

  foot();

  exit(0);
}
