/*
 *  ntdir.c
 *
 *  Copyright (C) 1995 Martin von Löwis
 */

#include <stdio.h>
#include <getopt.h>
#include <unistd.h>
#include <string.h>
#include "ntfs.h"
#include "config.h"

char *short_opts="lf:B:h";
struct option options[]={
	{"filesystem",1,0,'f'},
	{"long",0,0,'l'},
	{"bias",1,0,'B'},
	{"help",0,0,'h'}
};

void usage()
{
	fprintf(stderr,"ntdir [-f device] [--long] directory[/directory ...]\n");
}

/* display the directory ino */
void ntfs_print_dir(ntfs_inode* ino,int full)
{
	long long fileno;
	int first;
	char item[1000];
	int namelen;
	for(fileno=0,first=1;1;)
	{
		/* get the next entry */
		if(!ntfs_getdir_byposition(ino,&fileno,item))return;
		/* on the first iteration, we won't get any data */
		if(first){
			first=0;
			continue;
		}
		if(!full)
		{
			/* skip metadata */
			if(*(int*)item<16)
				continue;
			/* skip DOS only names */
			if(*(unsigned char*)(item+0x51) == 2)
				continue;
		}
		/* last access time? */
		print_time((long long*)(item+0x20));
		/* file size and mft record number */
		printf(" %10d %5d ",*(int*)(item+0x40),*(int*)item);
		namelen=*(unsigned char*)(item+0x50);
		/* file name */
		uniprint(item+0x52,namelen);
		putchar('\n');
	}
}

/* find file name in directory ino, return MFT record number if found */
int ntfs_find_file(ntfs_inode* ino,char *name)
{
	char item[1000];
	if(!ntfs_getdir_byname(ino,name,strlen(name),item))
		return -1;
	return *(int*)item;
}

int main(int argc,char *argv[])
{
	int c;
	char *device=0;
	char *name;
	ntfs_inode ino;
	int inum,bias=0;
	int full=0;

	opterr=1;
	while((c=getopt_long(argc,argv,short_opts,options,NULL))>0)
	switch(c)
	{
		case 'f': device=optarg;break;
		case 'l': full=1;break;
		case 'B': bias=strtol(optarg,NULL,0);break;
		case 'h': usage();exit(0);break;
	}
	name=argv[optind];
	if(!ntfs_open_volume(device,bias,1,0))return 1;
	/* walk the directory */
	inum=5;
	do{
		char *next;
		ntfs_init_inode(&ino,the_vol,inum);
		if(!name || !*name)break;
		next=strchr(name,'/');
		if(next){
			*next='\0';
			next++;
		}
		inum=ntfs_find_file(&ino,name);
		if(inum==-1){
			printf("%s not found\n",name);
			return 1;
		}
		name=next;
	}while(1);
	ntfs_print_dir(&ino,full);
}

