/*                               -*- Mode: C -*- 
 * cwsb.c -- Update the super block.
 * 
 * Author          : 
 * Created On      : Sun Jan 31 12:35:21 1999
 * Last Modified By: Peter Bosch
 * Last Modified On: Fri Apr  9 11:35:36 1999
 * Status          : Unknown, Use with caution!
 * 
 * Unless other notices are present in any part of this file
 * explicitly claiming copyrights for other people and/or 
 * organizations, the contents of this file is fully copyright 
 * (C) 1999 Peter Bosch, all rights reserved.
 */

#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

#include "cwif.h"

static char *progname;

extern int optind;
extern char *optarg;

static void
usage()
{
  fprintf(stderr, "Usage: %s device fdisk ftab did bsize nblocks dbmhi dbmlo\n",
	  progname);
  exit(1);
}

int
main(int argc, char **argv)
{
  int opt, fd, c, rv;
  cwsb_t sb;
  char *ofile;

  progname = argv[0];
  while ((opt = getopt(argc, argv, "?")) != EOF) {
    switch (opt) {
    case '?':
      usage();
    }
  }
  if (optind != argc - 8) usage();

  ofile         = argv[optind++];
  sb.sb_magic   = CWMAGIC;
  sb.sb_fdisk   = strtol(argv[optind++], (char **)NULL, 0);
  sb.sb_ftab    = strtol(argv[optind++], (char **)NULL, 0);
  sb.sb_did     = strtol(argv[optind++], (char **)NULL, 0);
  sb.sb_blocksz = strtol(argv[optind++], (char **)NULL, 0);
  sb.sb_nblocks = strtol(argv[optind++], (char **)NULL, 0);
  sb.sb_dbmhi   = strtol(argv[optind++], (char **)NULL, 0);
  sb.sb_dbmlo   = strtol(argv[optind++], (char **)NULL, 0);

  printf("%s: %08X FTAB %d.%d, DID %d, BS %d, NB %d, DBM %08X%08X.\nOK? (ny) ",
	 progname, sb.sb_magic, sb.sb_fdisk, sb.sb_ftab, sb.sb_did, 
	 sb.sb_blocksz, sb.sb_nblocks, sb.sb_dbmhi, sb.sb_dbmlo);
  fflush(stdout);
  c = getchar();
  if (c != 'y' && c != 'Y') {
    printf("%s: Aborted, nothing written\n", progname);
    exit(1);
  }

  fd = open(ofile, O_WRONLY);
  if (fd < 0) {
    fprintf(stderr, "%s: Cannot open %s: %s\n",
	    progname, ofile, strerror(errno));
    exit(1);
  }

  if (lseek(fd, CW_SBADDR * CW_SSIZE, SEEK_SET) < 0) {
    fprintf(stderr, "%s: Cannot seek on %s: %s\n",
	    progname, ofile, strerror(errno));
    exit(1);
  }

  if ((rv = write(fd, (const void *)&sb, sizeof(cwsb_t))) < 0) {
    fprintf(stderr, "%s: Cannot write super block to %s: %s\n",
	    progname, ofile, strerror(errno));
    exit(1);
  }

  if (rv != sizeof(cwsb_t)) {
    fprintf(stderr, 
	    "%s: Partially written super block.  Requested %d, wrote %d\n",
	    progname, sizeof(cwsb_t), rv);
    exit(1);
  }

  (void)close(fd);
  exit(0);
}
