/* $Id: mktar.c,v 1.6 2004/02/23 14:08:39 onoe Exp $ */

/*-
 * Copyright (c) 2000 Atsushi Onoe
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>

#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tar.h>
#include <unistd.h>
#include <zlib.h>

#define	TARBSIZE	512
#define	TARNMSIZE	100

struct tar_hdr {
	char	name[TARNMSIZE];
	char	mode[8];
	char	uid[8];
	char	gid[8];
	char	size[12];
	char	mtime[12];
	char	chksum[8];
	char	linkflag;
	char	linkname[TARNMSIZE];
};

int *nmbuf;
int nmsize, nment;

int
intcmp(const void *a, const void *b)
{
	return *(int *)a - *(int *)b;
}

void
addent(int n)
{
	int *p;

	if (nment == nmsize) {
		p = realloc(nmbuf, sizeof(*nmbuf) * (nmsize + 100));
		if (p == NULL) {
			fprintf(stderr, "realloc failed\n");
			exit(1);
		}
		nmbuf = p;
		nmsize += 100;
	}
	nmbuf[nment++] = n;
}

void
tar(FILE *fp, char *name, struct stat *st, caddr_t addr)
{
	int i, len;
	u_long sum;
	char hdrbuf[TARBSIZE];
	struct tar_hdr *h;

	memset(hdrbuf, 0, sizeof(hdrbuf));
	h = (struct tar_hdr *)hdrbuf;
	strlcpy(h->name, name, sizeof(h->name));
	snprintf(h->mode, sizeof(h->mode), "%06o ", st->st_mode);
	snprintf(h->uid, sizeof(h->uid), "%6o ", st->st_uid);
	snprintf(h->gid, sizeof(h->gid), "%6o ", st->st_gid);
	snprintf(h->size, sizeof(h->size), "%11llo ", st->st_size);
	snprintf(h->mtime, sizeof(h->mtime), "%11lo ", st->st_mtime);
	memset(h->chksum, ' ', sizeof(h->chksum));
	h->linkflag = REGTYPE;
	for (i = 0, sum = 0; i < sizeof(hdrbuf); i++)
		sum += hdrbuf[i];
	snprintf(h->chksum, sizeof(h->chksum), "%6lo", sum);
	fwrite(hdrbuf, sizeof(hdrbuf), 1, fp);

	if (st->st_size > 0) {
		len = (st->st_size + TARBSIZE - 1) / TARBSIZE * TARBSIZE;
		fwrite(addr, len, 1, fp);
	}
}

int
tarfile(FILE *fp, char *dname, int n)
{
	int fd;
	char fname[TARNMSIZE];
	struct stat stbuf;
	caddr_t addr;

	snprintf(fname, sizeof(fname), "%s/%d", dname, n);
	if ((fd = open(fname, O_RDONLY, 0)) == -1)
		return -1;
	if (fstat(fd, &stbuf) == -1) {
		close(fd);
		return -1;
	}
	if (stbuf.st_size > 0) {
		addr = mmap(NULL, stbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
		tar(fp, fname, &stbuf, addr);
		munmap(addr, stbuf.st_size);
	} else {
		tar(fp, fname, &stbuf, NULL);
	}
	close(fd);
	return 0;
}

void
tarindex(FILE *fp, char *dname)
{
	int dlen, ibsize, i, n;
	char fname[TARNMSIZE];
	struct stat stbuf;
	char *ibuf, *p, *q;

	dlen = strlen(dname);
	/* estimate */
	ibsize = (dlen + 1 + 5 + 1 + 6 + 1) * nment + 512 * 2;
	ibuf = malloc(ibsize);
	p = ibuf;
	for (i = 0; i < nment; i++) {
		if (p + 512 * 2 - ibuf > ibsize) {
			q = realloc(ibuf, ibsize + 512 * 8);
			if (!q)
				abort();
			ibuf = q;
			ibsize += 512 * 8;
		}
		n = sprintf(p, "%s/%d", dname, nmbuf[i]);
		if (stat(p, &stbuf) < 0)
			continue;
		p += n;
		p += sprintf(p, " %lld\n", stbuf.st_size);
	}
	snprintf(fname, sizeof(fname), "%s/.index", dname);
	stat(dname, &stbuf);
	stbuf.st_mode = S_IFREG | S_IRUSR | S_IRGRP | S_IROTH;
	stbuf.st_size = p - ibuf;
	tar(fp, fname, &stbuf, ibuf);
	free(ibuf);
}

void
doeof(FILE *fp)
{
	char buf[TARBSIZE];

	memset(buf, 0, sizeof(buf));
	fwrite(buf, sizeof(buf), 1, fp);
	fwrite(buf, sizeof(buf), 1, fp);
	fflush(fp);
}

int
main(int argc, char **argv)
{
	char *dname, *p;
	int i, n;
	DIR *dirp;
	struct dirent *dp;

	dname = argv[1];
	if ((dirp = opendir(dname)) == NULL) {
		fprintf(stderr, "opendir failed\n");
		exit(1);
	}
	while ((dp = readdir(dirp)) != NULL) {
		n = strtol(dp->d_name, &p, 10);
		if (n <= 0 || *p != '\0')
			continue;
		addent(n);
	}
	closedir(dirp);
	qsort(nmbuf, nment, sizeof(*nmbuf), intcmp);
	tarindex(stdout, dname);
	for (i = 0; i < nment; i++)
		tarfile(stdout, dname, nmbuf[i]);
	doeof(stdout);
	exit(0);
}
