cups-pdf PostProcessing script to get users from pGina
[safeq] / cups-pdf-find-owner.pl
diff --git a/cups-pdf-find-owner.pl b/cups-pdf-find-owner.pl
new file mode 100755 (executable)
index 0000000..54fafcc
--- /dev/null
@@ -0,0 +1,56 @@
+#!/usr/bin/perl
+use warnings;
+use strict;
+use autodie;
+
+use Data::Dump qw(dump);
+use File::Slurp;
+use DBI;
+
+my ($file, $local_user, $remote_user) = @ARGV;
+
+my $job_id = $1 if ( $file =~ m/job_(\d+)/ );
+
+die "can't find job_id in [$file]" unless $job_id;
+
+my $c_file = sprintf "/var/spool/cups/c%05d", $job_id;
+
+my $blob = read_file $c_file;
+
+my (undef,$ip) = split(/job-originating-host-name\x00/, $blob, 2);
+my $len = ord(substr($ip,0,1));
+$ip = substr($ip,1,$len);
+
+my $database = 'pGinaDB';
+my $hostname = '10.60.4.9';
+my $port     = 3306;
+my $user     = 'pGina';
+my $password = 'secret';
+
+my $dsn = "DBI:mysql:database=$database;host=$hostname;port=$port";
+my $dbh = DBI->connect($dsn, $user, $password);
+
+my $sth = $dbh->prepare(qq{
+       select * from pGinaSession where ipaddress = ? and logoutstamp is null order by loginstamp desc
+}) or die "prepare statement failed: $dbh->errstr()";
+$sth->execute($ip) or die "execution failed: $dbh->errstr()";
+if ( $sth->rows < 1 ) {
+       die "can't find IP for job $job_id";
+} elsif ( $sth->rows > 1 ) {
+       warn "ERROR: found $sth->rows() rows for $job_id, usng first one\n";
+}
+my $row = $sth->fetchrow_hashref();
+warn "## row = ",dump($row);
+
+$sth->finish;
+
+my $username = $row->{username} || die "no username in row = ",dump($row);
+
+my $spool = '/var/spool/cups-pdf/';
+mkdir "$spool/$username" if ( ! -e "$spool/$username" );
+my $filename_only = $file;
+$filename_only =~ s/^.*\///; # basename
+
+rename $file, "$spool/$username/$filename_only";
+
+exit 0;