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

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

char *short_opts="af:o:inCB:bc:";
struct option options[]={
	{"filesystem",1,0,'f'},
	{"offset",1,0,'o'},
	{"ignorecase",0,0,'i'},
	{"ascii",0,0,'a'},
	{"nodump",0,0,'n'},
	{"continue",0,0,'C'},
	{"cluster",1,0,'c'},
	{"blocksize",1,0,'B'},
	{"bytes",0,0,'b'}
};

void usage()
{
	fprintf(stderr,"ntgrep <options> string\n"
	"  --filesystem, -f device  use device as volume\n"
	"  --offset, -o n           start at offset n\n"
	"  --ignorecase, -i         do caseless search\n"
	"  --ascii, -a              search for ASCII string (default is Unicode)\n"
	"  --nodump, -n             display only location, don't dump context\n"
	"  --continue, -C           continue searching until end of volume\n"
	"  --cluster, -c n          start at cluster n\n"
	"  --blocksize, -b n        dump n bytes around the location\n"
	"  --bytes                  string is given as hex bytes\n"
	);
}

int main(int argc,char *argv[])
{
	int c;
	int ignore_case=0,ascii=0,cont=0,bytes=0;
	char *device=0;
	int offset=0,blocksize=GREP_DISPLAY_SIZE;
	int pos,length;
	char match[2048];
	char *in;

	opterr=1;
	while((c=getopt_long(argc,argv,short_opts,options,NULL))>0)
	switch(c)
	{
		case 'f': device=optarg;break;
		case 'o': offset=strtol(optarg,NULL,0);break;
		case 'i': ignore_case=1;break;
		case 'a': ascii=1;break;
		case 'C': cont=1;break;
		case 'c': offset=strtol(optarg,NULL,0)*512/*FIXME*/;break;
		case 'B': blocksize=strtol(optarg,NULL,0);break;
		case 'b': bytes=1;break;
	}
	if(optind==argc){
		usage();
		return 1;
	}
	in=argv[optind];
	if(bytes)
	{	char buf[3];
		buf[2]='\0';
		for(length=0;*in && *(in+1);in+=2,length++)
		{	buf[0]=in[0];
			buf[1]=in[1];
			match[length]=strtol(buf,NULL,16);
		}
	}
	else if(ascii)
	{	strcpy(match,in);
		length=strlen(in);
	}else
		for(length=0;*in;in++,length+=2)
		{	match[length]=*in;
			match[length+1]='\0';
		}
	ntfs_open_volume(device,0,0,1);
	do{
		pos=grep(offset,-1,match,length,ignore_case);
		if(pos==-1)
			fprintf(stderr,"Not found\n");
		else{
			printf("0x%X\n",pos);
			pos=(pos/blocksize)*blocksize;
			dump(pos,pos,blocksize);
			offset=pos+blocksize;
		}
	}while(cont);
}

