/*
 * nbmd5.c  -  MD5 checksum program
 *
 * Copyright (C) 2004-2007 Gero Kuhlmann <gero@gkminix.han.de>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * $Id: nbmd5.c,v 1.6 2007/01/06 18:31:20 gkminix Exp $
 */


/* This will include all necessary system header files */
#include <common.h>
#include <nblib.h>



/*
 * Print usage
 */
static void usage __F_NOARGS
{
  fprintf(stderr, "usage: %s [-t] [-b] [<srcfile>]\n", progname);
  exit(1);
}



/*
 * Main program
 */
int main __F((argc, argv), int argc AND char **argv)
{
  char *fname = NULL;
  int binary = TRUE;
  int infile, flags, i;
  size_t insize;
  __u8 buffer[1024];
  __u8 digest[MD5_DIGEST_SIZE];

  /* Get program name */
  if ((progname = strrchr(argv[0], '/')) == NULL)
	progname = argv[0];
  else
	progname++;

  /* Get options from command line */
  for (i = 1; i < argc; i++)
	if (!strcmp(argv[i], "-b"))
		binary = TRUE;
	else if (!strcmp(argv[i], "-t"))
		binary = FALSE;
	else if (argv[i][0] == '-')
		usage();
	else if (fname != NULL)
		usage();
	else
		fname = argv[i];

  /* Open input file */
  flags = O_RDONLY | (binary ? O_BINARY : 0);
  if (fname == NULL) {
	infile = STDIN_FILENO;
	binary = FALSE;
  } else if ((infile = open(fname, flags)) < 0) {
	fprintf(stderr, "%s: unable to open input file\n", progname);
	exit(1);
  }

  /* Read input file and compute MD5 checksum */
  md5init();
  while ((insize = read(infile, buffer, sizeof(buffer))) > 0)
	md5update(buffer, insize);
  md5final(digest);
  if (infile != STDIN_FILENO)
	close(infile);

  /* Print the checksum to stdout */
  for (i = 0; i < MD5_DIGEST_SIZE; i++)
	printf("%02x", (digest[i] & 0xff));
  printf(" %c%s\n", (binary ? '*' : ' '), (fname == NULL ? "-" : fname));
  return(0);
}

