#!/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] ID\n";
my $q = "";
GetOptions ('q|queue=s' => \$q);

my @ids = @ARGV[0 .. $#ARGV];

if (!$q){
    $q = "DEFAULT";
}
if (!@ids) {
    print $usage;
    exit 1
}


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;
}
my @jobs = $printer->getJobs(0, 0);
foreach my $id(@ids){
if ($id eq "all") {
    foreach $id(@jobs) {
	cancel_job($id, $printer);
    }
}
elsif ($id eq "current") {
    $id = $jobs[0];
    cancel_job($id, $printer);
}
elsif ($id eq "last") {
    $id = $jobs[-1];
    cancel_job($id, $printer);
}
else {
    foreach my $item(@jobs) {
	if($item =~ /$id/){
	    cancel_job($item, $printer);
	}
    }
}
}

sub cancel_job {
    my ($id, $printer) = @_;
    my $job_ref = $printer->getJob($id);
    my $title = $job_ref->{'title'};
    $printer->cancelJob($id);

    print "Canceled job '$title' (id $id)\n";
 
}
