#!/usr/bin/perl

# Written by Jessica Hamrick (C) 2010

use strict;
use warnings;

use Net::CUPS;
use Net::CUPS::Destination;
use Getopt::Long;
use Image::ExifTool qw(ImageInfo);

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

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

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

if (!$q){
    $q = "DEFAULT";
}
if (!@files) {
    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 ($jobid, $title);

foreach my $file(@files) {
    if ($file =~ m|http://www\.youtube\.com/watch\?v=|) {
	open FILE, ">", "/tmp/gutenbach-youtube" or die "Couldn't create temporary file";
	print FILE $file;
	$title = $file;
	$file = "/tmp/gutenbach-youtube";
	$printer->addOption("copies", 42);
    }
    else {
	my $fileinfo = ImageInfo($file);
	my $magic = $fileinfo->{FileType};

	if ($magic && exists($fileinfo->{Title}) && exists($fileinfo->{Artist}) && exists($fileinfo->{Album})) {
	    $title = $fileinfo->{'Title'}." - ".$fileinfo->{'Artist'}." - ".$fileinfo->{'Album'};
	}
	else {
	    $title = $file;
	}
    }

    $jobid = $printer->printFile($file, $title);
    
    if ($jobid) {
	print "Sent job '$title' (id $jobid)\n";
    }
    else {
	print "Error sending job '$title'\n";
    }
}
