#!/usr/bin/perl

# Written by Jessica Hamrick (C) 2010

use strict;
use warnings;

use Net::CUPS;
use Net::CUPS::Destination;

my $usage = "Usage: gbq QUEUE ID\n";

my $q = $ARGV[0];
my $id = $ARGV[1];

if (!$q or !$id) {
    print $usage;
    exit 1
}

my $configpath = "$ENV{'HOME'}/.gutenbach/$q";
if (! -e $configpath) {
    print "Queue '$q' does not exist!\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");
my @jobs = $printer->getJobs(0, 0);

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 {
    cancel_job($id, $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";
}
