#!/usr/bin/python

#     printconf - silly script to set up every printer attached to the
#                 system with zero fuss.
#     Copyright (C) 2004 Chris Lawrence <lawrencc@debian.org>

#     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 2 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, write to the Free Software
#     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# $Id: printconf,v 1.2 2004/06/23 07:39:50 lordsutch Exp $

from foomatic import detect, foomatic
import re
import os

# regex for invalid characters in queue names to be filtered
_invalidre = re.compile(r'([^A-Za-z0-9_])')

def cleanup_name(model):
    model = model.lower().replace(' ', '_')
    newmod = _invalidre.sub('', model)
    return newmod

# CUPS needs printer.conf established before lpadmin will work properly
os.system('touch /etc/cups/printer.conf')

printdb = foomatic.get_printer_db()
conns = detect.printer_connections()

for (device, detectdata, devdesc, detectdesc) in conns:
    # Skip everything we don't have autodetection data for
    if not detectdata: continue

    # Get the IEEE 1284 printer description
    desc = detectdata.get('description')
    if not desc: continue

    model = detectdata.get('model', desc)

    pdbinfo = printdb.autodetect_ids.get(desc)
    # Unknown printer; probably should print a message here asking
    # people to contribute this information to foomatic-db
    if not pdbinfo: continue

    prefdriver = pdbinfo.get('driver')
    # Unsupported printer; barf something here
    if not prefdriver: continue

    data = {'connect' : device, 'description' : desc,
            'name' : cleanup_name(model), 'location' : devdesc,
            'driver' : prefdriver }

    #print data
    foomatic.setup_queue(data)
    # Queue X is now set up with name based on the IEEE model
    # some sort of message here would be nice

# After loop, reinit CUPS
os.system('/usr/sbin/invoke-rc.d cupsys reload')    
