Skip to content

Instantly share code, notes, and snippets.

@scottwalters
Created October 22, 2019 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottwalters/f570fd8dc979022c6bbcd4f84a0e7b1e to your computer and use it in GitHub Desktop.
Save scottwalters/f570fd8dc979022c6bbcd4f84a0e7b1e to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use strict;
use warnings;
use Carp;
$SIG{USR1} = \&Carp::confess;
$SIG{CHLD} = 'IGNORE';
use Net::LPR;
$< == 0 or do exec 'sudo', $0, @ARGV;
sub opt ($) { scalar grep $_ eq $_[0], @ARGV }
sub arg ($) { my @a=args(@_); return () unless @a; return $a[0]; }
sub args ($) { grep { my $x = $_ eq $_[0] ... /^-/; $x !~ /E/ and $x and $x > 1; } @ARGV; }
my $fn = '-';
my $ip = '192.168.0.24';
while( @ARGV ) {
if( $ARGV[0] eq '-P' ) {
shift @ARGV;
$ip = shift @ARGV;
} else {
# die "should only be a filename left at this point" if @ARGV > 1;
$fn = shift @ARGV;
}
}
my $data = '';
my $lp = new Net::LPR(
StrictRFCPorts => 0,
RemoteServer => $ip,
RemotePort => 515,
PrintErrors => 1,
RaiseErrors => 1,
);
if($fn ne '-') {
open my $fh, '<', $fn or die "$fn: $!";
read $fh, $data, -s $fh;
close $fh;
} else {
1 while read STDIN, $data, 1024, length $data;
}
$data .= " " unless $data =~ m/ $/;
$lp->connect();
my $jobkey = $lp->new_job();
$lp->job_mode_postscript($jobkey);
$lp->send_jobs('lp'); # root mode command
# $data =~ s/(?<!\r)\n(?!\r)/\r\n/gs; # fix line endings?
# eg: %!PS-Adobe-2.0 EPSF-2.0
if( $data !~ m/^%!PS-Adobe/) {
if( opt '-w' ) {
use Text::Wrap 'fill';
$Text::Wrap::columns = 79;
$data = fill('', '', $data);
}
# convert text to PS
use IO::Handle;
$fn = "/tmp/lpr_$$.ps";
open my $fh, '|-', "/usr/local/bin/text2ps > $fn" or die $!;
$fh->print($data) or die $!;
close $fh or warn $!;
# read it back in again
open $fh, '<', $fn or die $!;
$data = join '', readline $fh;
length $data or die;
close $fh;
}
# just locks up apparently on the fork(), which doesn't make any sense
# update: running -d:Trace, it locks up on trying to read from $reader
# use IPC::Open2;
# use IO::Handle;
# open2(my $reader, my $writer, '/usr/local/bin/text2ps'); # pretty sure this is correct
# if(fork) {
#warn "parent";
# # parent
# # $data = join '', readline $reader;
# $data = '';
# 1 while read $reader, $data, 1024, length $data;
# } else {
#warn "child";
# # child
# $writer->print( $writer ) or die $!;
# close $writer or die $!;
# sleep 30; exit;
# }
$lp->job_send_control_file($jobkey); # job mode command
$lp->job_send_data($jobkey, $data, length $data);
$lp->disconnect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment