#! /usr/bin/env python
# -*- coding: ISO-8859-15 -*-

# autopykota : script to automate user creation in PyKota
#
# PyKota - Print Quotas for CUPS and LPRng
#
# (c) 2003, 2004, 2005 Jerome Alet <alet@librelogiciel.com>
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# $Id: autopykota 1819 2005-09-27 18:34:31Z jerome $
#
#

import sys
import os

from pykota.tool import PyKotaTool, PyKotaToolError, PyKotaCommandLineError, crashed, N_

__doc__ = N_("""autopykota v%(__version__)s (c) %(__years__)s %(__author__)s

A tool to automate user account creation and initial balance setting.

THIS TOOL MUST NOT BE USED IF YOU WANT TO LIMIT YOUR USERS BY PAGE QUOTA !

command line usage :

  THIS TOOL MUST NOT BE USED FROM THE COMMAND LINE BUT ONLY AS PART
  OF AN external policy IN pykota.conf
  
  autopykota { -i | --initbalance value } 

options :

  -v | --version       Prints autopykota's version number then exits.
  -h | --help          Prints this message then exits.
  
  -i | --initbalance b Sets the user's account initial balance value to b.
                       If the user already exists, actual balance is left
                       unmodified. If unset, the default value is 0.
""")

class AutoPyKota(PyKotaTool) :
    """A class for the automat."""
    def main(self, arguments, options) :
        """Main entry point."""
        os.environ["PATH"] = "%s:/bin:/usr/bin:/usr/local/bin:/opt/bin:/sbin:/usr/sbin" % os.environ.get("PATH", "")
        username = os.environ.get("PYKOTAUSERNAME")
        printername = os.environ.get("PYKOTAPRINTERNAME")
        if (username is None) or (printername is None) :
            raise PyKotaToolError, "Either the username or the printername is undefined. Fatal Error."
        else :
            printer = self.storage.getPrinter(printername)
            user = self.storage.getUser(username)
            if user.Exists :
                self.logdebug("User %s already exits." % username) 
                if printer.Exists :
                    userpquota = self.storage.getUserPQuota(user, printer)
                    if userpquota.Exists :
                        # we should never get there, unless autopykota was launched manually
                        self.logdebug("User %s's quota entry on printer %s already exists. Nothing to do." % (username, printername))
                        return 0
                    else :    
                        printersnames = [printer.Name] + [p.Name for p in self.storage.getParentPrinters(printer)]
                        self.logdebug("Creating a quota entry for user %s on printers %s" % (username, printersnames))
                        return os.system('edpykota --add --printer "%s" "%s"' % (','.join(printersnames), username))
                else :
                    self.logdebug("Printer %s doesn't exist. Creating printer %s and a quota entry for user %s on printer %s." % (printername, printername, username, printername))
                    return os.system('edpykota --add --printer "%s" "%s"' % (printername, username))
            else :
                if printer.Exists :
                    printersnames = [printer.Name] + [p.Name for p in self.storage.getParentPrinters(printer)]
                else :    
                    printersnames = [printer.Name]
                self.logdebug("User %s doesn't exist yet." % username)
                self.logdebug("Creating user %s's account with balance %s and quota entries on printers %s" % (username, options["initbalance"], printersnames))
                return os.system('edpykota --add --limitby balance --balance "%s" --printer "%s" "%s"' % (options["initbalance"], ','.join(printersnames), username))
    
if __name__ == "__main__" :    
    retcode = 0
    try :
        defaults = { \
                     "initbalance" : 0.0
                   }
        short_options = "vhi:"
        long_options = ["help", "version", "initbalance="]
        
        # Initializes the command line tool
        automat = AutoPyKota(doc=__doc__)
        automat.deferredInit()
        
        # parse and checks the command line
        (options, args) = automat.parseCommandline(sys.argv[1:], short_options, long_options)
        
        # sets long options
        options["help"] = options["h"] or options["help"]
        options["version"] = options["v"] or options["version"]
        options["initbalance"] = options["i"] or options["initbalance"] or defaults["initbalance"]
        
        if options["help"] :
            automat.display_usage_and_quit()
        elif options["version"] :
            automat.display_version_and_quit()
        elif args :    
            raise PyKotaCommandLineError, "autopykota doesn't accept non option arguments !"
        else :
            retcode = automat.main(args, options)
    except KeyboardInterrupt :        
        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
    except PyKotaCommandLineError, msg :    
        sys.stderr.write("%s : %s\n" % (sys.argv[0], msg))
    except SystemExit :        
        pass
    except :
        try :
            automat.crashed("autopykota failed")
        except :    
            crashed("autopykota failed")
        retcode = -1

    try :
        automat.storage.close()
    except (TypeError, NameError, AttributeError) :    
        pass
        
    sys.exit(retcode)    
