#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include "omfs.h"
#include "dirscan.h"
#include "check.h"
#include "crc.h"
#include "fix.h"
#include "bits.h"
#include "io.h"

static int on_node(dirscan_t *d, dirscan_entry_t *entry, void *user)
{
	char *name = escape(entry->inode->name);

	printf("inode: %*c%s%c s:%llx h:%d c:%d p:%llx b:%llx\n", 
		entry->level*2, ' ', name,
		(entry->inode->type == OMFS_DIR) ? '/' : ' ',
		swap_be64(entry->inode->head.self), entry->hindex,
		swap_be16(entry->inode->head.crc), 
		entry->parent, entry->block); 
	free(name);

	return 0;
}

int dump_fs(FILE *fp)
{
	int bsize;
	omfs_super_t super;
	omfs_root_t root;
	omfs_info_t info = { 
		.dev = fp, 
		.super = &super,
		.root = &root
	};

	if (omfs_read_super(fp, &super))
	{
		printf ("Could not read super block\n");
		return 0;
	}
	if (omfs_read_root_block(fp, &super, &root))
	{
		printf ("Could not read root block\n");
		return 0;
	}

	printf ("label: %s\n", super.name);
	printf ("size:  %llu %d-byte blocks\n", swap_be64(super.num_blocks), 
        swap_be32(super.blocksize));
	putchar('\n');

	bsize = (swap_be64(info.super->num_blocks) + 7) / 8;

	if (dirscan_begin(&info, on_node, NULL) != 0)
	{
		printf("Dirscan failed\n");
		return 0;
	}
    return 1;
}
