#!/usr/bin/perl

# Written by Jessica Hamrick (C) 2010

use strict;
use warnings;

my $usage = "Usage: gbr QUEUE FILES\n";

my $q = $ARGV[0];
my @files = @ARGV[1 .. $#ARGV];

if (!$q or !@files) {
    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>;
}

$ENV{CUPS_SERVER}="$host";

foreach my $file(@files) {
    if ($file =~ m|http://www\.youtube\.com/watch\?v=|) {
	open(LP, "|-", "lp", "-d$queue") or die "Couldn't execute lp command";
	print LP "$file";
	close LP;
    }
    else {
	my $pid = open(LP, "-|");
	if (not $pid) {
	    my @args = ("lp", "-d$queue", "$file");
	    exec(@args) or die "Couldn't execute lp command";
	}
    }

    print "Sent job '$file'\n";
}
