#! /usr/bin/perl
#
#   Copyright 2010 Free Software Foundation, Inc.
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Script to put in /lib/udev to start/stop printers
# (Rewritten in perl to avoid dependency on Python)

use Sys::Syslog;
use Sys::Syslog qw(:standard :macros);

# Make a full /dev/xxx pathname out of device

sub fullpath {
    my $dev = shift;
    return $dev if $dev =~ /^\//;
    join('/', ('/dev', $dev));
}

################ START HERE

if ($#ARGV != 0) {
    print "Usage: $0 add|remove\n";
    exit 1;
}

$action = shift @ARGV;

# Only interested in local printers hence -l

unless (open(DEVS, "gspl-plist -l -F %p::%d::%t|"))  {
    print "Cannot open printer list command\n";
    exit 2;
}

# Possible printers - store as arrays of pairs ptrname,dev

@possptrs = ();

while (<DEVS>)  {
    chop;
    my ($ptrname, $dev, $state) = split(/\s*::\s*/);

    # Ignore network style devices

    next if $dev =~ /<.*>/;
    
    if ($action eq 'add') {
	push @possptrs, [$ptrname, $dev] if $state eq 'halted' || $state eq 'error' || $state eq 'offline';
    }
    else  {
	push @possptrs, [$ptrname, $dev] unless $state eq 'halted' || $state eq 'error' || $state eq 'offline';
    }
}

close DEVS;

# Exit OK if nothing to do

exit 0 if $#possptrs < 0;

# Open log and save details

openlog $0, 0, LOG_LPR;
setlogmask(LOG_UPTO(LOG_DEBUG));

if ($action eq 'add')  {
    for my $p (@possptrs) {
	my ($ptr, $dev) = @$p;
	my $fdev = fullpath($dev);
	if (-c $fdev) {
	    $ret = system("gspl-start -l '$dev' $ptr");
	    if  ($ret != 0)  {
		syslog(LOG_ERR, "Unable to start $ptr");
	    }
	    else  {
		syslog(LOG_INFO, "Started $ptr on $fdev");
	    }
	}
    }
}
else  {
    for my $p (@possptrs) {
	my ($ptr, $dev) = @$p;
	my $fdev = fullpath($dev);
	unless (-c $fdev) {
	    $ret = system("gspl-pstop -l '$dev' $ptr");
	    if  ($ret != 0)  {
		syslog(LOG_ERR, "Unable to stop $ptr");
	    }
	    else  {
		syslog(LOG_INFO, "Stopped $ptr on $fdev");
	    }
	}
    }
}	
