/*
 * Copyright (c) 1986, 1987, 1988 by The Trustees of Columbia University
 * in the City of New York.  Permission is granted to any individual or
 * institution to use, copy, or redistribute this software so long as it
 * is not sold for profit, provided this copyright notice is retained.
 */

#ifndef lint
static char *rcsid = "$Header: mkversion.c,v 1.12 88/08/11 06:02:44 chris Exp $";
#endif

/*
 * mkversion:
 * create a version string for MM
 */

#include "config.h"
#include "osfiles.h"
#include "compat.h"

#define PROGNAME "Columbia MM"		/* program name */

#ifndef MM_MAJOR
#define MM_MAJOR 0
#endif
#ifndef MM_MINOR
#define MM_MINOR 0
#endif
#ifndef MM_EDIT
#define MM_EDIT 0
#endif

int maj = MM_MAJOR, min = MM_MINOR, edit = MM_EDIT;

main (argc, argv) 
int argc;
char **argv;
{
    FILE *fp;
    char *user, *host, *whoami (), *getlocalhostname (), *daytime ();
    int fn = 0;

    if (argc > 2)
	usage ();

    scanversion ();

    if (argc == 2) {
	if (argv[1][0] == '-' || argv[1][0] == '+')
	    ++argv[1];
	switch (argv[1][0]) {
	  case 'e':
	  case 'm':
	  case 'M':
	    fn = argv[1][0];
	    if (argv[1][1] == 0)
		break;
	  default:
	    usage ();
	}
    }

    switch (fn) {
      case 'M':
	maj++;
	min = edit = 0;
	break;
      case 'm':
	min++;
	edit = 0;
	break;
      case 'e':
	edit++;
	break;
    }
    
    printf ("Updating version.h for %s %d.%d(%d)\n", PROGNAME, maj, min, edit);

    fp = fopen ("version.h", "w");
    if (!fp) {
	perror ("mkversion: fopen: version.h");
	exit (1);
    }
	
    fprintf (fp, "/*\n * %s\n */\n\n",
	     "This file is automatically generated by \"mkversion\"");

    fprintf (fp, "#define MM_MAJOR %d\n", maj);
    fprintf (fp, "#define MM_MINOR %d\n", min);
    fprintf (fp, "#define MM_EDIT %d\n", edit);
    fprintf (fp, "#define MM_VERSION \"%s, version %d.%d(%d)-Beta\"\n",
	     PROGNAME, maj, min, edit);

    user = whoami ();
    host = getlocalhostname ();

    fprintf (fp, "#define MM_COMPILED \"");
    if (user) {
	if (host)
	    fprintf (fp, "by %s@%s ", user, host);
	else
	    fprintf (fp, "by %s ", user);
    }
    fprintf (fp, "on %s\"\n", ctad ((time_t) 0));
    
    if (fclose (fp) == EOF) {
	perror ("mkversion: fclose");
	exit (1);
    }

    exit (0);
}

usage ()
{
    fprintf (stderr, "usage: mkversion [ e | m | M ]\n");
    exit (1);
}

scanversion ()
{
    int n;
    char line[512];
    FILE *fp;

    fp = fopen ("version.h", "r");
    if (fp) {
	while (fgets (line, sizeof line, fp) == line) {
	    if (sscanf (line, "#define MM_MAJOR %d", &n) == 1)
		maj = n;
	    else if (sscanf (line, "#define MM_MINOR %d", &n) == 1)
		min = n;
	    else if (sscanf (line, "#define MM_EDIT %d", &n) == 1)
		edit = n;
	}
	fclose (fp);
    }
}
