root / pykota / trunk / bin / autopykota @ 3288

Revision 3288, 6.7 kB (checked in by jerome, 16 years ago)

Moved all exceptions definitions to a dedicated module.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1#! /usr/bin/env python
2# -*- coding: UTF-8 -*-
3#
4# PyKota : Print Quotas for CUPS
5#
6# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
7# This program is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program.  If not, see <http://www.gnu.org/licenses/>.
19#
20#
21# $Id$
22#
23#
24
25import sys
26import os
27
28from pykota.errors import PyKotaToolError, PyKotaCommandLineError
29from pykota.tool import PyKotaTool, crashed, N_
30
31__doc__ = N_("""autopykota v%(__version__)s (c) %(__years__)s %(__author__)s
32
33A tool to automate user account creation and initial balance setting.
34
35THIS TOOL MUST NOT BE USED IF YOU WANT TO LIMIT YOUR USERS BY PAGE QUOTA !
36
37command line usage :
38
39  THIS TOOL MUST NOT BE USED FROM THE COMMAND LINE BUT ONLY AS PART
40  OF AN external policy IN pykota.conf
41 
42  autopykota { -i | --initbalance value }
43
44options :
45
46  -v | --version       Prints autopykota's version number then exits.
47  -h | --help          Prints this message then exits.
48 
49  -i | --initbalance b Sets the user's account initial balance value to b.
50                       If the user already exists, actual balance is left
51                       unmodified. If unset, the default value is 0.
52
53  -e | --email addr    Sets the user's e-mail address.
54 
55""")
56
57class AutoPyKota(PyKotaTool) :
58    """A class for the automat."""
59    def main(self, arguments, options) :
60        """Main entry point."""
61        username = os.environ.get("PYKOTAUSERNAME")
62        printername = os.environ.get("PYKOTAPRINTERNAME")
63        if (username is None) or (printername is None) :
64            raise PyKotaToolError, "Either the username or the printername is undefined. Fatal Error."
65        else :
66            printer = self.storage.getPrinter(printername)
67            if not printer.Exists :
68                self.logdebug("Creating printer %s which doesn't exist yet." % printername)
69                os.system('pkprinters --add --description "printer created from autopykota" "%s"' % printername)
70                printer = self.storage.getPrinterFromBackend(printername)
71                if printer.Exists :
72                    self.logdebug("Printer %s created successfully." % printername)
73                else :   
74                    self.logdebug("Impossible to create printer %s." % printername)
75                printernames = [printername]
76            else :   
77                printernames = [printer.Name] + [p.Name for p in self.storage.getParentPrinters(printer)]
78           
79            user = self.storage.getUser(username)
80            if not user.Exists :
81                self.logdebug("Creating user %s which doesn't exist yet." % username)
82                if (options["email"] is None) :
83                    os.system('pkusers --add --limitby balance --balance "%s" --description "user created from autopykota" "%s"' % (options["initbalance"], username))
84                else :
85                    os.system('pkusers --add --limitby balance --balance "%s" --email "%s" --description "user created from autopykota" "%s"' % (options["initbalance"], options["email"], username))
86                   
87                user = self.storage.getUserFromBackend(username)
88                if user.Exists :
89                    self.logdebug("User %s created successfully." % username)
90                else :   
91                    self.logdebug("Impossible to create user %s." % username)
92               
93            if user.Exists and printer.Exists :   
94                userpquota = self.storage.getUserPQuota(user, printer)
95                if not userpquota.Exists :
96                    self.logdebug("Creating a print quota entry for user %s on printers %s" % (username, printernames))
97                    os.system('edpykota --add --printer "%s" "%s"' % (','.join(printernames), username))
98                    userpquota = self.storage.getUserPQuotaFromBackend(user, printer)
99                    if userpquota.Exists :
100                        self.logdebug("User %s's print quota entry on printer %s created successfully." % (username, printername))
101                        return 0
102                    else :   
103                        self.logdebug("Impossible to create user %s's print quota entry on printer %s." % (username, printername))
104                        return -1
105                else :
106                    self.logdebug("User %s's print quota entry on printer %s already exists. Nothing to do." % (username, printername))
107                    return 0
108            else :       
109                return -1
110               
111if __name__ == "__main__" :   
112    retcode = 0
113    try :
114        defaults = { \
115                     "initbalance" : 0.0
116                   }
117        short_options = "vhi:e:"
118        long_options = ["help", "version", "initbalance=", "email="]
119       
120        # Initializes the command line tool
121        automat = AutoPyKota(doc=__doc__)
122        automat.deferredInit()
123       
124        # parse and checks the command line
125        (options, args) = automat.parseCommandline(sys.argv[1:], short_options, long_options)
126       
127        # sets long options
128        options["help"] = options["h"] or options["help"]
129        options["version"] = options["v"] or options["version"]
130        options["initbalance"] = options["i"] or options["initbalance"] or defaults["initbalance"]
131        options["email"] = options["e"] or options["email"]
132       
133        if options["help"] :
134            automat.display_usage_and_quit()
135        elif options["version"] :
136            automat.display_version_and_quit()
137        elif args :   
138            raise PyKotaCommandLineError, "autopykota doesn't accept non option arguments !"
139        else :
140            retcode = automat.main(args, options)
141    except KeyboardInterrupt :       
142        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
143        retcode = -3
144    except PyKotaCommandLineError, msg :   
145        sys.stderr.write("%s : %s\n" % (sys.argv[0], msg))
146        retcode = -2
147    except SystemExit :       
148        pass
149    except :
150        try :
151            automat.crashed("autopykota failed")
152        except :   
153            crashed("autopykota failed")
154        retcode = -1
155
156    try :
157        automat.storage.close()
158    except (TypeError, NameError, AttributeError) :   
159        pass
160       
161    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.