#!/usr/bin/perl

# Written by Jessica Hamrick (C) 2010

use strict;
use warnings;

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

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!  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");
my ($jobid, $title);

foreach my $file(@files) {
    if ($file =~ m|http://www\.youtube\.com/watch\?v=|) {
	open FILE, ">", "/tmp/gutenbach-youtube\n" 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) {
	    $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";
    }
}
