#!/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 @args;

if ($id eq "all") {
    @args = ("cancel", "-a", "$queue");
}
elsif ($id eq "current") {
    my $cups = Net::CUPS->new();
    $cups->setServer("$host");
    my $printer = $cups->getDestination("$queue");
    my @jobs = $printer->getJobs(0, 0);
    my $id = $jobs[0];
    @args = ("cancel", "$id", "$queue");
}
else {
    @args = ("cancel", "$id", "$queue");
}
$ENV{CUPS_SERVER}="$host";
exec (@args) or die "Couldn't execute cancel command";
