static char RCSid[]="$Header: /etc/Dump/src/RCS/wlabel.c,v 1.2 89/02/03 17:43:49 viktor Exp Locker: viktor $" ;
/*
 *  Tape label manipulation     (c)  Copyright  Viktor Dukhovni 25/Jan/1989
 *                                   This program may be freely redistributed
 *				     in source or binary form, so long as this
 *				     copyright notice remains intact in the 
 *			             source file,  or is acknowledged in 
 *				     documentation supplied with the binary.
 *
 *  Modified by Stuart Levy, April & May 1989.
 *
 * $Log:	wlabel.c,v $
 * Revision 1.2  89/02/03  17:43:49  viktor
 * uncommented out the initial MTREW,  left behind from debugging.
 * 
 * Revision 1.1  89/02/03  17:36:31  viktor
 * Initial revision
 * 
 */

#include <sys/ioctl.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/mtio.h>
static struct mtop mtop = { MTREW, 1 } ;
#include <fcntl.h>
#include <stdio.h> 

extern char *getenv();

#define BLK (63 * 1024)

char buf[BLK];

main(argc,argv)
	char **argv;
{
	char *TAPE;
	int fd;
	int rewrite;
	int i, c;

	if (argc <= 1 || argv[1][0] != '-' ||
				((c = argv[1][1]) != 'i' && c != 'r') {
		fprintf(stderr,"\
Usage:	%s -i [/dev/nrrt0]  -- write initial table-of-contents file on $TAPE\n\
	%s -r [/dev/nrrt0]  -- rewrite <=63k table-of-contents from stdin\n\
WARNING: on some tape drives '-r' just erases the t.o.c., know before using!\n\
One of -i or -r is required, don't destroy tapes casually.\n",argv[0]) ;
		exit(1) ;
	}
	rewrite = (c == 'r');

	TAPE=getenv("TAPE") ;
	if (argc > 2) TAPE = argv[2];
	if (TAPE == NULL) TAPE = "/dev/nrrt0";

	if((fd = open(TAPE,O_WRONLY)) == -1) {
		perror("Cannot open tape") ;
		exit(1) ;
	}

	if(ioctl(fd,MTIOCTOP,&mtop) == -1 ) {
		perror(TAPE);
		exit(1) ;
	}

	if(rewrite) {
		i = 0;
		while((c = read(0, &buf[i], BLK-i)) > 0)
			i += c;
	} else {
		long now = time(0);
		struct tm *tm = localtime(&now);

		sprintf(buf,
		    "Table of contents %02d.%02d.%02d.%02d.%02d %d toc\n",
		    tm->tm_year % 100, tm->tm_mon + 1, tm->tm_mday,
		    tm->tm_hour, tm->tm_min,
		    BLK*100);
	}

	/* Write out the header a few times,  will read back only one
	 * record,  but do not want to run into erased tape
	 * 100*63k = 6.3Mb
	 */
	for(i = rewrite ? 25 : 100; --i >= 0; ) {
		if ( write(fd,buf,BLK) == -1 ) {
			perror("TAPE: write error:") ;
			exit(1) ;
		}
	}
	if(rewrite) {
		if(ioctl(fd,MTIOCTOP,&mtop) == -1 ) {
			perror(TAPE);
			exit(1) ;
		}
	}
	close(fd);
}
