/* Itp: read contents of a itp archive.
 * Author: Warren Toomey wkt@cs.adfa.edu.au
 * $Revision: 1.2 $
 * 
 * This works on a little-endian machine. You will probably have endian
 * trouble with the 2-, 3- and 4-octet fields in the tpdir structure.
 */

#include "defines.h"
#define BLKSIZ 512				/* Size of itp tape blocks */

/* itp tape directory entry */
struct tpdir {
    char pathname[48];				/* Filename of file */
    uint16_t mode;				/* Unix mode */
    uint8_t uid;				/* Owner of file */
    uint8_t gid;				/* Group of file */
    char unused1;
    uint8_t size[3];				/* Size in bytes */
    uint32_t modtime;				/* Time of last modification */
    uint16_t tapeaddr;				/* Beginning block on tape */
    uint16_t checksum;				/* Checksum */
};

/* We build a linked list when
 * reading in the tape
 */
struct tlist {
    struct tpdir tdir;
    int size;
    struct tlist *next;
};

void mkrecursdir(char *name);

void swap16(i)
   uint16_t *i;
{
   char *a, b;
 
   a= (char *)i; b= a[0]; a[0]= a[1]; a[1]=b;
}
 
void swap32(i)
   uint32_t *i;
{
   char *a, b;
 
   a= (char *)i; b= a[0]; a[0]= a[3]; a[3]=b; b=a[1]; a[1]=a[2]; a[2]=b;
}

void checktypes()
{
 if (sizeof(int8_t)!=1)	  { printf("Wrong size for type int8_t\n"); exit(1); }
 if (sizeof(uint8_t)!=1)  { printf("Wrong size for type uint8_t\n"); exit(1); }
 if (sizeof(int16_t)!=2)  { printf("Wrong size for type int16_t\n"); exit(1); }
 if (sizeof(uint16_t)!=2) { printf("Wrong size for type uint16_t\n"); exit(1); }
 if (sizeof(int32_t)!=4)  { printf("Wrong size for type int32_t\n"); exit(1); }
 if (sizeof(uint32_t)!=4) { printf("Wrong size for type uint32_t\n"); exit(1); }
}

void usage()
{
    printf("Usage: itp [t|x] filename\n"); exit(1);
}

int main(argc, argv)
    int argc;
    char *argv[];
{
    char buf[BLKSIZ];
    FILE *zin, *zout;
    int toc = 1;
    int extract = 0;
    uint32_t size;
    struct tlist *thead = NULL, *tent, *this;
    int blockbytes;
    uint8_t a, *b;
    struct utimbuf utbuf;

    checktypes();			/* Check size of our typedefs */
    if (argc != 3) usage();		/* Give usage if wrong # args */
    if (argv[1][0] == 't') {
	toc = 1; extract = 0;
    }					/* Either extract of give contents */
    if (argv[1][0] == 'x') {
	toc = 0; extract = 1;
    }
    zin = fopen(argv[2], "r");
    if (zin == NULL) { perror("Opening input file"); exit(1); }

    /* Read in the tape directory entries */
    while (1) {
	tent = (struct tlist *) malloc(sizeof(struct tlist));
	tent->next = NULL;
	if ((fread(&(tent->tdir), sizeof(struct tpdir), 1, zin)) != 1) {
	    printf("fread failed on itp archive %s\n",argv[2]);
	    break;
	}

	/* If entry has no name, we've reached end of the list */
	if (tent->tdir.pathname[0] == '\0') break;

	/* Get the size of the file */
	size = tent->tdir.size[0] * 65536 + tent->tdir.size[2] * 256
	  + tent->tdir.size[1];
	tent->size = size;

#ifdef BIGEND
        /* Convert multibyte fields */
        swap16(&(tent->tdir.mode));
        swap16(&(tent->tdir.tapeaddr));
        /* Convert the modification time into a normal Unix time value */
        b = (uint8_t *) & (tent->tdir.modtime);
        a = b[0]; b[0] = b[1]; b[1] = a;
        a = b[2]; b[2] = b[3]; b[3] = a;
#else
        /* Convert the modification time into a normal Unix time value */
        b = (uint8_t *) & (tent->tdir.modtime);
        a = b[0]; b[0] = b[2]; b[2] = a;
        a = b[1]; b[1] = b[3]; b[3] = a;
#endif

	/* Print the table of contents */
	if (toc) { printf("%s %o %d %d %d at %d %s", tent->tdir.pathname,
		   tent->tdir.mode, tent->tdir.uid, tent->tdir.gid, size,
		   tent->tdir.tapeaddr, ctime((time_t *)&(tent->tdir.modtime)));
	}

	/* Add entry to the list */
	if (thead == NULL) thead = this = tent;
	else { this->next = tent; this = tent; }
    }

    if (extract)
	for (this = thead; this; this = this->next) {

	    /* Print the file's name on stdout */
	    printf("x %s %d, ", this->tdir.pathname, this->size);

	    /* Convert file size into # of tape blocks */
	    blockbytes = BLKSIZ * ((this->size + 511) / 512);
	    printf("%d blockbytes\n", blockbytes);
	    if (this->size==0) continue;

	    /* Seek to the beginning of the file */
	    fseek(zin, BLKSIZ * this->tdir.tapeaddr, SEEK_SET);
	    size = this->size;

	    /* Open the output file */
	    zout = fopen(this->tdir.pathname, "w");
	    if (zout == NULL) {
		/* Ok, try making the directories */
		mkrecursdir(this->tdir.pathname);
		zout = fopen(this->tdir.pathname, "w");
		if (zout == NULL) {
		    printf("Can't open %s for writing\n", this->tdir.pathname);
		    continue;
		}
	    }
	    
	    /* Read and write the blocks from the archive to the file */
	    while (size) {
		if ((fread(&buf, BLKSIZ, 1, zin)) != 1) {
		    printf("Error reading block for %s\n", this->tdir.pathname);
		    break;
		}
		if (size < BLKSIZ) { fwrite(&buf, size, 1, zout); size = 0; }
		else { fwrite(&buf, BLKSIZ, 1, zout); size -= BLKSIZ; }
	    }

	    /* Close the file */
	    fclose(zout);

	    /* Set up the file's mode, owner, group and modification time */
	    chmod(this->tdir.pathname, this->tdir.mode);
	    chown(this->tdir.pathname, this->tdir.uid, this->tdir.gid);
	    utbuf.actime = utbuf.modtime = this->tdir.modtime;
	    utime(this->tdir.pathname, &utbuf);
	}
    exit(0);
}

/* Build the directory needed to create the file.
 * We cheat by using mkdir -p.
 */
void 
mkrecursdir(char *name)
{
    char *c;
    char buf[300];

    c = strrchr(name, '/');
    if (c) {
	*c = '\0';
	sprintf(buf, "/bin/mkdir -p %s", name); system(buf);
	*c = '/';
    }
}
