! Simple PURGE utility for new-style Fred-O/S, intended to run against
! the new-style filestores (running it against the old-style filestores
! will be a no-op).

%option "-nodiag-nocheck-nons"
%include "Inc:FS.Imp"
%include "inc:fsutil.imp"

%owninteger n = 0

%externalroutinespec delete(%string(255)file)

%routine delete file(%string(255) file)
%constinteger monitoring=1
   %integer x
      %on 3 %start
$if monitoring=0
         printstring("Delete "); printstring(file)
$finish
         printstring(" failed: ");  printstring(event_message)
         newline
         %return
      %finish
$if monitoring#0
      printstring("Delete ");  printstring(file)
$finish
      delete(file)
$if monitoring#0
      newline
$finish
      n = n + 1
%end

%routine read line(%string(*)%name s)
   %integer ch
      s = ""
      %cycle
         read symbol(ch)
         %exit %if ch = NL
         s = s . to string(ch)
      %repeat
%end

%begin
   %string(255) directory, file, filespec, param, junk
      %on 3, 9 %start
         %if event_event = 3 %start
            printstring("Purge "); printstring(directory)
            printstring(" fails: ");  printstring(event_message)
            newline
            %stop
         %finish
         write(n, 0);  printstring(" file")
         print symbol('s') %if n # 1
         printstring(" purged");  newline
         %stop
      %finish
      param = CLI param
      !Parameter:
      !If no parameter is given all files in the current directory are purged.
      !The parameter is assumed to be a file name in the current directory
      !unless it ends in ":" in which case it is taken to mean all files in
      !the specified directory.   If a full file spec is given then the obvious
      !thing is done.    The file spec may contain wild cards.  The directory
      !may not.
      
      directory="" %and filespec=param %unless param -> directory.(":").filespec
      directory = directory.":".junk %while filespec -> junk.(":").filespec

      directory = "." %if directory=""
      directory = directory . ":"
      open input(3, directory);  select input(3)
      %cycle
         read line(file)
         %if file -> file . (":-") -
         %and (filespec="" %or matches(file, filespec)) -
         %then delete file(directory . file . ":-1")
      %repeat
%end %of %program
