/*
**  guardfile.c by Daniel Balster
**
**  guardfile is a file guardian, which once launched watches all file access and
**  helps you to debug illegal accesses.
**
**  usage: guardfile <filename> [<filename> ... ]
**
**
**
*/

#include <exec/types.h>
#include <exec/memory.h>
#include <dos/dos.h>
#include <dos/notify.h>
#include <clib/exec_protos.h>
#include <clib/dos_protos.h>

UBYTE *V[] = "$VER: guardfile v1.0\0";

VOID _main( VOID )
{
    struct Library *DOSBase;
    ULONG  args[4] = {0,0,0,0};

    if( DOSBase = OpenLibrary( "dos.library", 37L ) )
    {
	struct Process *process = FindTask( 0 );

	if( process->pr_CLI )
	{
	    struct RDArgs *rdargs;

	    if( rdargs = ReadArgs( "NAME", args, NULL ) )
	    {
		if( args[0] )
		{
		    struct NotifyRequest *nr;

		    if( nr = (struct NotifyRequest *) AllocVec( sizeof(struct NotifyRequest), MEMF_PUBLIC|MEMF_CLEAR ) )
		    {
			ULONG signals, signal;

			if( signal = AllocSignal( -1 ) )
			{
			    nr->nr_Name 			=   (STRPTR) args[0];
			    nr->nr_Flags			=   NRF_SEND_SIGNAL;
			    nr->nr_stuff.nr_Signal.nr_Task	=   FindTask( NULL );
			    nr->nr_stuff.nr_Signal.nr_SignalNum =   signal;

			    StartNotify( nr );

			    signals = Wait( (1L<<signal) | SIGBREAKF_CTRL_C );

			    if( signals & SIGBREAKF_CTRL_C )
				PutStr( "CTRL-C\n" );

			    if( signals & signal )
				PutStr( "ACCESS\n" );

			    EndNotify( nr );
			    FreeSignal( signal );
			}
			FreeVec( nr );
		    }
		    else PrintFault( ERROR_NO_FREE_STORE, 0 );
		}
		else PrintFault( ERROR_REQUIRED_ARG_MISSING, 0 );

		FreeArgs( rdargs );
	    }
	    else PrintFault( IoErr(), NULL );
	}
	else
	{
	    /*	workbench stuff.
		do not add an icon, it should only be used by shell */

	    WaitPort( &process->pr_MsgPort );
	    ReplyMsg( GetMsg( &process->pr_MsgPort ) );
	}

	CloseLibrary( DOSBase );
    }
}

