#!/usr/bin/perl

# Written by Jessica Hamrick (C) 2010

use strict;
use warnings;

use Net::CUPS;
use Net::CUPS::Destination;
use Getopt::Long;

my $usage = "Usage: gbq [-q QUEUE]\n";

my $q = "";
GetOptions ('q|queue=s' => \$q);

if (!$q) {
    $q = "DEFAULT";
}

my $configpath = "$ENV{'HOME'}/.gutenbach/$q";
if (! -e $configpath) {
    print "Queue '$q' does not exist!  Did you forget to add it with 'gutenbach-client-config'?\n";
    exit 1;
}

my ($host, $queue);

if (-r $configpath) {
    local $/;
    my $fh;
    open $fh, $configpath;
    eval <$fh>;
}

my $cups = Net::CUPS->new();
$cups->setServer("$host");
my $printer = $cups->getDestination("$queue");

unless( $printer){
    print "Cannot access queue $q...do you have network connectivity and permission to view the queue?\n";
    exit 1;
}
print "Queue listing for queue '$queue' on '$host'\n\n";
printf ("%-8s%-15s%s\n","Job","Owner","Title");
print "-"x70 . "\n";
my @jobs = $printer->getJobs(0, 0);
my ($job_ref, $jobid);

foreach $jobid(@jobs) 
{       
	$job_ref = $printer->getJob($jobid);
	my $id = $job_ref->{'id'};
	my $user = $job_ref->{'user'};
	my $title = $job_ref->{'title'};

	printf ("%-8s%-15s%s\n","$id",substr("$user",0,15),substr("$title",0,47));
}
