#!@SHELL@
#
# faxrm <job ids>
#
# remove faxes with job_id passed on the command line (if writable)
#
# There are still a lot rough edges - but it works, and should give you an
# idea how to improve it
#
# SCCS: $Id: faxrm.in,v 4.4 1997/05/28 12:39:57 gert Exp $ Copyright (C) 1994 Gert Doering

FAX_SPOOL=@FAX_SPOOL@
FAX_SPOOL_OUT=@FAX_SPOOL_OUT@
#
# echo program that will accept escapes (bash: "echo -e", sun: /usr/5bin/echo)
#
echo="@ECHO@"

if [ ! -d $FAX_SPOOL_OUT ]
then
    echo "$FAX_SPOOL_OUT does not exist" >&2
    exit 1
fi

cd $FAX_SPOOL_OUT

interactive=""
if [ "X$1" = "X-i" ]
then
    interactive="i"
    shift
fi

if [ $# -eq 0 ]
then
    echo "usage: faxrm [-i] job-id ..."
    exit 1
fi
    
for jobid
do
    if [ ! -d "$jobid" ]
    then
        echo "$jobid: no such job found." >&2
        continue
    fi
#
# check directory permissions
#
    if [ ! -w $jobid ]
    then
	echo "$jobid: permission denied, job not removed." >&2
	continue
    fi
#
# old job?
#
    if [ -f $jobid/JOB.done ]
    then
	echo "$jobid: job already sent." >&2
	continue
    fi

#
# check for suspended jobs
#
    if [ -f $jobid/JOB.suspended ]
    then
	if [ ! -w $jobid/JOB.suspended ]
	then
	    echo "$jobid: permission denied, job not removed." >&2
	    continue
	fi
	test -d $jobid/.source-files && rm -rf $jobid/.source-files
	rm -f $jobid/*
	rmdir $jobid
	continue
     fi
#
# not an old / suspended job
#

#
# lock it
#
    if mv $jobid/JOB $jobid/JOB.locked 2>/dev/null
    then
	trap "mv -f $jobid/JOB.locked $jobid/JOB" 0
#
# it's locked, now remove it
#
	if [ ! -w $jobid/JOB.locked ]
	then
	    echo "$jobid: permission denied, job not removed." >&2
	    continue
	fi
	test -d $jobid/.source-files && rm -rf $jobid/.source-files
	rm -f $jobid/*
	rmdir $jobid
    else
#
# locking didn't work
#
	if [ -f $jobid/JOB.locked ]
	then
	    echo "$jobid: job is locked, try again later." >&2
	    continue
	fi
	if [ ! -f $jobid/JOB ]
	then
	    echo "$jobid: no JOB file, job already clean." >&2
	    rmdir $jobid
	fi
    fi
#
# end for (all jobs)
done

trap "" 0

