/* -*- Mode: C++; tab-width: 8; c-basic-offset: 8 -*-
 *
 */

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "LFSFileSystem.h"
#include "Exception.h"

#define INODES_PER_BLOCK (BLOCK_SIZE / sizeof(ino_t))

int
main(int /* argc */, char* argv[])
{
	int fd;
	if ((fd = open(argv[1], O_RDONLY)) < 0) {
		fprintf(stderr, "%s: unable to mount %s: %s\n",
			argv[0], argv[1], strerror(errno));

		return 1;
	}

	// XXX should make this so that we can parse as many of these
	// as there are...
	unsigned short segnr = atoi(argv[2]);

	int error = 0;
	try {
		CLFSFileSystem fs(fd);
		fs.Mount();
		CLFSSMap* smap = fs.GetSMap();

		CLFSSegment* segment = smap->GetSegment(segnr);

		unsigned long addr = fs.SegmentToAddr(segnr);
		addr += segment->SummaryBlockAddr();

		do {
			CLFSBlock* block = new CLFSBlock(fs, addr);
			block->Read();

			ino_t *ino = (ino_t*) block->GetData();

			unsigned int index = 0;
			while (index < INODES_PER_BLOCK && *ino) {
				printf("%d,%ld\n", segnr, *ino);
				++index;
				++ino;
			}
			delete block;

			if (! *ino)
				break;

			++addr;
		} while (1);

		delete segment;
		delete smap;
	}
	catch (CException* ex) {
		fprintf(stderr, "%s: %s\n", argv[0], ex->GetMessage());
		delete ex;
	}
	close(fd);
	return error;
}

