#!/usr/bin/python

"""
A DCM-like thing that will add cluster and dorm print queues not
already served by cups.mit.edu and reconfigure ones that are already
there.
"""

import os
import sys
import getopt
from subprocess import Popen, call, PIPE
import re
import moira
import cups

quiet=False

models = {
    'HP8100': '/usr/share/ppd/openprinting/HP/HP_LaserJet_8150_Series.ppd.gz',
    'LOCAL': '/dev/null',
    'default': '/usr/share/ppd/openprinting/HP/HP_LaserJet_8150_Series.ppd.gz'
}

def processPrinter(fields):
    """
    Examine an output line from `qy gprn` and use that to reconfigure
    the CUPS queue to match what Moira knows.
    """
    queue = fields['name']
    location = fields['location']
    rm = fields['rm']
    hwtype = fields['hwtype']
    
    uri = 'lpd://%s/%s' % (rm, fields['rp'])
    description = queue
#    description = '%s - cups.mit.edu' % queue
    
    call(['/usr/bin/foomatic-configure', 
          '-n', queue, 
          '-N', description,
          '-L', location, 
          '-c', uri,
          '--ppd', models.get(hwtype, models['default']),
          '-d', 'Postscript',
          '-o', 'HPOption_Duplexer=True',
#          '-o', 'Duplex=DuplexNoTumble'
          ])
    if not quiet:
        print 'Configured %s' % queue

def usage():
    print "Usage: load_queues [--verbose] [--quiet] [queue ...]"
    print

def main():
    moira.connect()
    try:
        opts, args = getopt.getopt(sys.argv[1:],
                                  'qv',
                                  ['quiet', 'verbose'])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for o, a in opts:
        if o in ('-q', '--quiet'):
            quiet = True
        if o in ('-v', '--verbose'):
            quiet = False
    if args != []:
        for queue in args:
            for queue_info in moira.query('gprn', queue):
                processPrinter(queue_info)
    else:
        for queue_info in moira.query('gprn', '*'):
            if queue_info['type'] in ['CLUSTER', 'DORM'] and \
                    queue_info['ka'] != '1':
                processPrinter(queue_info)

if __name__ == '__main__':
    main()
