#!/usr/local/bin/perl
# $Id: testauth_send_pgp,v 1.1 1999/10/24 19:47:54 papowell Exp papowell $
# LPRng authorization test program
# 
#   - used to send and decode authenticated information
#
#   command line:
#   /filter -C/F -P printer -n sender_id -A authtype -R receiver_id -Ttempfile
#   The sender_id and receiver_id are URL escaped values
#   tempfile is a path to a tempfile for working information
# 
#    FD Options Purpose
#    0  R/W     socket connection to remote host (R/W)
#    1  W       for status report about authentication
#    2  W       error log
# 
#   Actions:
# 1. encode the tempfile for transfer to the remote host.
# 2. Write a line with the number of bytes in the encoded file
#    followed by the encoded file to FD 0.
# 3. Read the return status from FD 0 and send to the tempfile. 
#    If necessary, decode the return status.
# 

use Getopt::Std;
use FileHandle;
use Shell;
use URI::Escape;


# /filter -C -P printer -n sender_id -A authtype -R remote_id -Ttempfile
my($debug, %args,$key,$value,$v, $tempfile, $temp, $printfile,
	@lines, $print, $buf, $socket, @s, $len, $test, $recv, $send );

$|= 1;
$debug = 1;
$test = 0;

getopts("CFD:P:n:A:R:T:",\%args);
if( defined($line = $args{'D'}) ){
	$debug = 1 if( $line =~ /debug/ );
	$test = 1 if( $line =~ /test/ );
}

if( $debug ){
	$v = "$0";
	foreach $key (sort keys %args){
		$v .= " $key=$args{$key}"
	}
	print STDERR $v . "\n";
	print STDERR "ARGV @ARGV\n";
	for $i (sort keys %ENV ){
		print STDERR "ENV $i=$ENV{$i}\n";
	}
}

$recv = uri_unescape($args{'R'});
$send = uri_unescape($args{'n'});

$temp = new FileHandle;
$print = new FileHandle;
$socket = new FileHandle;

$tempfile = $args{'T'};
if( not $tempfile ){
	warn "missing tempfile\n";
	exit(1);
}
if( not $recv ){
	warn "missing receiver id\n";
	exit(1);
}
if( not $send ){
	warn "missing sender id\n";
	exit(1);
}

$line = "pgp +force +batch -sea $tempfile '$recv' -u '$send' -o $tempfile 2>&1";
print STDERR "$line\n" if $debug;
eval{ @lines = `$line`; };
if( $@ ){
	print STDERR "eval error '$@'\n";
	exit(1);
} elsif( $? ){
	$line = join( '', @lines);
	chomp($line);
	$i = $? >> 8;
	print STDERR "pgp error '$line'\n";
	exit(1);
}

if( $debug ){
	print STDERR "pgp returned:\n";
	for( $i = 0; $i < @lines; ++$i ){
		$line = $lines[$i];
		chomp $line;
		print STDERR " [$i] '$line'\n";
	}
}

exit(1) if $test;

$socket->open(">&0") or die "cannot open fd 0";
$socket->autoflush(1);

@s = stat $tempfile or die "cannot stat '$tempfile'";
$len = $s[7];
print STDERR "LENGTH $len\n" if $debug;

print $socket "$len\n";

$temp->open("<$tempfile") or die "cannot open '<$tempfile'";
while( read $temp, $buf, 10240 ){
	print STDERR "SENDING '$buf'\n" if $debug;
	print $socket $buf;
}

$socket->close();

print STDERR "FINISHED SENDING\n" if $debug;
$socket->open("<&0") or die "cannot reopen open fd 0";

while( defined($buf = <$socket>) ){
	print STDERR "RECEIVED '$buf'\n" if $debug;
	print $buf;
}
print STDERR "FINISHED RECEIVING\n" if $debug;
