/* cfdel.c -- delete entry in a cff filesystem */

#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include "cff.h"

static void *it;
static char basefile[200];
static char *lastpart;

static void
Usage()
{
	cfputs("Usage: cfdel  cfpath\n");
}
static void
lose_backslashes(char *cp)
{
	while(*cp) {
		if(*cp == '\\')
			*cp = '/';
		++cp;
	}
}
static void
del_entry()
{
CFSTAT sbuf;
	if(cfsubstat(it, lastpart, &sbuf) != OK)
	{
		cfprintf("cfdel: %s does not exist\n", lastpart);
		return;
	}
	if(sbuf.st_mode & M_CHUNK)
		cfdelete(it, lastpart, strlen(lastpart));
	else {
	void *df = cfsubopen(it, lastpart, F_RDWR, NULL);
		cfunlink(df, NULL);
	}
}
static void *
open_cffile(char *name)
{
int namlen = strlen(name);
int i;
void *itt = NULL;
long obbits = OB_XFILE;
	
	for(i = namlen-1; i >= 0; --i)
	{
		if(		name[i] == 'f'
			&&	name[i-1] == 'f'
			&&	name[i-2] == 'c'
			&&	name[i-3] == '.')
		{
#ifdef SKELETON
			oxlink_nouse_library(name);
#endif
			strncpy(basefile, name, i+1);
			if(name[i+1] != '/' || name[i+2] == 0)
			{
				cfprintf("cfdel: no element in path\n");
				return NULL;
			}
			lastpart = &name[i]+2;

			obbits = cfobtype(basefile);
			if(obbits == 0) {
				cfprintf("cfdel: cannot open %s\n", basefile);
			} else if(obbits & OB_ROOTDIR) {
				itt = cfopen(basefile, F_RDWR, NULL);
			} else {
				cfprintf("cfdel: %s is not a cff filesystem\n", basefile);
				return NULL;
			}
			break;
		}
	}
	if(obbits & OB_XFILE) {
		cfprintf("cfdel: %s is not a cff filesystem\n", name);
		return NULL;
	}

	return itt;
}
#ifdef SKELETON
int
cfdel(int argc, char **argv)
#else
void
main(int argc, char **argv)
#endif
{
int i,j;

#ifndef SKELETON
	cfinit("cfdel", 400, NULL);
#endif
	/* Get the switches */
	for(i = 1; i < argc; ++i)
	{
		if(argv[i][0] == '-')
		{
			for(j=1; argv[i][j]; ++j)
			{
				switch(argv[i][j])
				{
					default:
						break;
				}
			}/* END: for(j) */
			/* Trim switch */
			for(j = i; j < argc-1; ++j)
				argv[j] = argv[j+1];
			--argc; 			
			--i;
		}/* END: if('-') */
	}/* END: for(argc) (get switches) */

	if(argc >= 2) {
		lose_backslashes(argv[1]);
		if((it = open_cffile(argv[1])) != (void*)0)
		{
			del_entry();
			cfclose(it);
		} 
		exit(0);
	}
	else Usage();
#ifndef SKELETON
	cfexit();
	exit(0);
#else
	return 0;
#endif
}

