/* ProtectTree V1.01
 * Protect recursivly files against writing and execution
 * (C) 1992 Christophe PASSUELLO
 * Mon Feb  8 21:07:05 1993
 */

#include <exec/types.h>
#include <exec/memory.h>
#include <libraries/dos.h>
#include <libraries/arpbase.h>
#include <mytypes.h>


#define PROTECTTREEVER	"ProtectTree V1.00"


CPTR ArpBase = NULL;		/* pointer to arp.library */


struct ExtAnchorPath
{
	struct AnchorPath Path;
	char buffer[255];
} *Ancre=NULL;


/*
 * free ressources
 */
VOID clean_exit()
{
	if (Ancre) FreeMem(Ancre, sizeof(struct ExtAnchorPath));
	if (ArpBase) CloseLibrary(ArpBase);
	exit(0);
}


/*
 * Presentation
 */
VOID Presentation()
{
	puts("\x9b1;33;40m" PROTECTTREEVER "\x9b0;31;40m\x9b3;32;40m");
	puts("\x9b0;31;40m(C) 1992 by Christophe PASSUELLO, All Rights Reserved.\n");
}


/*
 * Print usage
 */
VOID Usage()
{
	puts("Usage: ProtectTree <FilePattern> [-all]");
	puts("  <FilePattern> can be a file or a pattern as *.h");
	puts("  -all option enables recursive protection.");
}


/*
 * Main
 */
main(int ac, char **av)
{
	STRPTR FilePattern=NULL;
	STRPTR FileName=NULL;
	ULONG Mask=0;
	BOOL all=FALSE;

	/* Open the arp.library V39 */
	if (!(ArpBase = OpenLibrary(ArpName, ArpVersion)))
	{
		puts("You need arp.library V39+");
		clean_exit();
	}

	Presentation();

	if ((ac <= 1) || (ac > 3))
	{
		Usage();
		clean_exit();
	}

	/* Parsing of arguments */
	FilePattern = av[1];

	if ((ac == 3) && (stricmp(av[2], "-all") == 0))
		all = TRUE;

	/* main routine  */
	if (Ancre = AllocMem(sizeof(struct ExtAnchorPath), MEMF_CLEAR|MEMF_PUBLIC))
	{
		LONG error;
		UWORD nbfiles=0;
		UWORD nbfilesprot=0;

		/* init Ancre */
		Ancre->Path.ap_BreakBits = SIGBREAKF_CTRL_C;
		Ancre->Path.ap_StrLen = 255;
		Ancre->Path.ap_Flags = APF_DoWild;

		Mask = FIBF_WRITE|FIBF_EXECUTE;
	
		error = FindFirst(FilePattern, Ancre);
		while(!error)
		{
			FileName = Ancre->Path.ap_Buf;

			/* check if directory */
			if (Ancre->Path.ap_Info.fib_DirEntryType >= 0)
			{
				if (all)
				{
					/* recursive protection */
					if (!(Ancre->Path.ap_Flags & APF_DidDir))
						Ancre->Path.ap_Flags |= APF_DoDir;

					Ancre->Path.ap_Flags &= ~APF_DidDir;
				}
			}
			else
			{
				nbfiles++;
				if (SetProtection(FileName, Mask))	/* Protection of file */
					nbfilesprot++;
			}

			if (Ancre->Path.ap_Flags & APF_ItsWild == 0)		/* Stop if single file */
				break;

			error=FindNext(Ancre);
		}

		FreeAnchorChain(&(Ancre->Path));
		switch(error)
		{
			case ERROR_BREAK:
				puts("***BREAK");

			case 0:
			case ERROR_NO_MORE_ENTRIES:
				printf(" - %d files protected succesfully on %d files.\n", nbfilesprot, nbfiles);
				break;

			case ERROR_OBJECT_NOT_FOUND:
				puts("File not found.");
				break;

			case ERROR_BUFFER_OVERFLOW:
				puts("Path too long!");
				break;

			default:
				printf("IO error %ld!\n",error);
				break;
		}

		clean_exit();
		/* THE END */
	}
	else
	{
		puts("Not enough memory");
		clean_exit();
	}
}
