: run this script through /bin/sh

RP500=ETCDIR/rp500

NAME="$1"
if [ -z "$NAME" ]; then
    echo "usage: xrpcomp name [arguments for comp]" 2>&1
    exit 1
fi

DB=".rpdb"
if [ ! -s "$DB" ]; then
    DB="$HOME/.rpdb"
fi
if [ ! -s "$DB" ]; then
    echo "unable to read $DB" 2>&1
    exit 1
fi

C=/tmp/rp$$.comp	S=/tmp/rp$$.sh	O=/tmp/rp$$.orig
trap "rm -f $C $S $O" 0 1 2 3 13 15

cp /dev/null $S
gawk -v NAME="$NAME" -v S="$S" -v O="$O" '
function rev(f) {
    s = ""
    for (l = length(f); l > 0; l--)
	s = s "." substr(f, l, 1)
    return substr(s, 2, length(s) - 1)
}

BEGIN	{
	    RS= ""; FS = "\n"
	}
	{
	    if (NR == 1) {
		from = $2
		gsub("Recipient[        ]*:", "Originator:", from);
		orig = "\r\n" from
		for (i = 3; i <= NF; i++)
		    orig = orig "\r\n" $i;
		printf orig "\r\n" > O
	    }

	    if ($1 != NAME)
		next
	    for (i = 2; i <= NF; i++) {
		if (match($i, "Facsimile[ 	]*:") > 0) {
		    fax = substr($i, RSTART+RLENGTH)
		    gsub("[ 	+-]", "", fax)

		    printf "ADDR=\"remote-printer@%s.tpc.int\"\n", rev(fax) > S
		    printf "To: remote-printer@%s.tpc.int\n", rev(fax)
		    printf "Subject:\n"
		    printf "--------\n"
		    printf "#<application/remote-printing\n"

		    recip = $2
		    for (i = 3; i <= NF; i++)
			recip = recip "\r\n" $i;
		    printf "%s\r\n%s\r\n", recip, orig

		    printf "#\n"
		    exit(0)
		}
	    }
	}' < $DB > $C
. $S
if [ -z "$ADDR" ]; then
    echo "recipient \"$NAME\" not in $DB, checking X.500..." 2>&1
    $RP500 "$NAME" > $C
    RC=$?
    if [ $RC = 1 ]; then
	exit 1
    elif [ $RC = 0 ]; then
	cat $O >> $C
	echo "#" >> $C
    else
	echo "error searching X.500" 2>&1
	exit 1
    fi
fi

shift
comp -form $C $* -editor rpprompter
