root / pykota / trunk / bin / edpykota @ 758

Revision 758, 10.7 kB (checked in by jalet, 21 years ago)

Better handle wrong or bad command line arguments

  • 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
3# PyKota Print Quota Editor
4#
5# PyKota - Print Quotas for CUPS
6#
7# (c) 2003 Jerome Alet <alet@librelogiciel.com>
8# You're welcome to redistribute this software under the
9# terms of the GNU General Public Licence version 2.0
10# or, at your option, any higher version.
11#
12# You can read the complete GNU GPL in the file COPYING
13# which should come along with this software, or visit
14# the Free Software Foundation's WEB site http://www.fsf.org
15#
16# $Id$
17#
18# $Log$
19# Revision 1.11  2003/02/08 09:42:44  jalet
20# Better handle wrong or bad command line arguments
21#
22# Revision 1.10  2003/02/08 09:39:20  jalet
23# typos
24#
25# Revision 1.9  2003/02/08 09:38:06  jalet
26# Badly placed test
27#
28# Revision 1.8  2003/02/07 22:53:57  jalet
29# Checks if printer name is valid before adding it
30#
31# Revision 1.7  2003/02/07 22:17:58  jalet
32# Incomplete test
33#
34# Revision 1.6  2003/02/07 22:13:13  jalet
35# Perhaps edpykota is now able to add printers !!! Oh, stupid me !
36#
37# Revision 1.5  2003/02/06 14:49:04  jalet
38# edpykota should be ok now
39#
40# Revision 1.4  2003/02/06 14:28:59  jalet
41# edpykota should be ok, minus some typos
42#
43# Revision 1.3  2003/02/06 10:47:21  jalet
44# Documentation string and command line options didn't match.
45#
46# Revision 1.2  2003/02/06 10:39:23  jalet
47# Preliminary edpykota work.
48#
49# Revision 1.1  2003/02/05 21:41:09  jalet
50# Skeletons added for all command line tools
51#
52#
53#
54
55import sys
56
57from pykota import version
58from pykota.tool import PyKotaTool, PyKotaToolError
59
60__doc__ = """edpykota v%s (C) 2003 C@LL - Conseil Internet & Logiciels Libres
61A Print Quota editor for PyKota.
62
63command line usage :
64
65  edpykota [options] user1 user2 ... userN
66  edpykota [options] group1 group2 ... groupN
67
68options :
69
70  -v | --version       Prints edpykota's version number then exits.
71  -h | --help          Prints this message then exits.
72 
73  -a | --add           Adds users and/or printers if they don't
74                       exist on the Quota Storage Server.
75                       
76  -u | --users         Edit users print quotas, this is the default.
77 
78  -P | --printer p     Edit quotas on printer p only. Actually p can
79                       use wildcards characters to select only
80                       some printers. The default value is *, meaning
81                       all printers.
82 
83  -g | --groups        Edit groups print quotas instead of users.
84                         
85  -p | --prototype u|g Uses user u or group g as a prototype to set
86                       print quotas
87                       
88  -S | --softlimit sl  Sets the quota soft limit to sl pages.                       
89 
90  -H | --hardlimit hl  Sets the quota hard limit to hl pages.
91 
92examples :                             
93
94  $ edpykota -p jerome john paul george ringo
95 
96  This will set print quotas for the users john, paul, george and ringo
97  to the same values than user jerome. User jerome must exist.
98 
99  $ edpykota --printer lp -S 50 -H 60 jerome
100 
101  This will set jerome's print quota on the lp printer to a soft limit
102  of 50 pages, and a hard limit of 60 pages. If either user jerome or
103  printer lp doesn't exist on the Quota Storage Server then nothing is done.
104
105  $ edpykota --add --printer lp -S 50 -H 60 jerome
106 
107  Same as above, but if either user jerome or printer lp doesn't exist
108  on the Quota Storage Server they are automatically added.
109  WARNING : the CUPS PPD file for this printer must still be modified
110            manually, as well as pykota's configuration file for a
111            new printer to be managed successfully.
112           
113  $ edpykota -g -S 500 -H 550 financial support           
114 
115  This will set print quota soft limit to 500 pages and hard limit
116  to 550 pages for groups financial and support on all printers.
117
118This program is free software; you can redistribute it and/or modify
119it under the terms of the GNU General Public License as published by
120the Free Software Foundation; either version 2 of the License, or
121(at your option) any later version.
122
123This program is distributed in the hope that it will be useful,
124but WITHOUT ANY WARRANTY; without even the implied warranty of
125MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
126GNU General Public License for more details.
127
128You should have received a copy of the GNU General Public License
129along with this program; if not, write to the Free Software
130Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
131
132Please e-mail bugs to: %s""" % (version.__version__, version.__author__)
133       
134class EdPyKota(PyKotaTool) :       
135    """A class for edpykota."""
136    def isValidPrinterName(self, printername) :
137        """Checks if a printername is valid."""
138        import string
139        if printername[0] in string.ascii_letters :
140            validchars = string.ascii_letters + string.digits + "-_"
141            for c in printername[1:] :
142                if c not in validchars :
143                    return 0
144            return 1       
145        return 0
146       
147    def main(self, names, options) :
148        """Edit user or group quotas."""
149        printernames = self.storage.getMatchingPrinters(options["printer"])
150        if not printernames :
151            pname = options["printer"]
152            if options["add"] and pname :
153                if self.isValidPrinterName(pname) :
154                    self.storage.addPrinter(pname)
155                else :   
156                    raise PyKotaToolError, "Invalid printer name %s" % pname
157            else :
158                raise PyKotaToolError, "There's no printer matching %s" % pname
159        softlimit = hardlimit = None   
160        if options["softlimit"] :
161            try :
162                softlimit = int(options["softlimit"].strip())
163            except ValueError :   
164                raise PyKotaToolError, "Invalid softlimit value %s." % options["softlimit"]
165        if options["hardlimit"] :
166            try :
167                hardlimit = int(options["hardlimit"].strip())
168            except ValueError :   
169                raise PyKotaToolError, "Invalid hardlimit value %s." % options["hardlimit"]
170        if (softlimit is not None) and (hardlimit is not None) and (hardlimit < softlimit) :       
171            # error, exchange them
172            self.logger.log_message("Hard limit %i is less than soft limit %i, values will be exchanged." % (hardlimit, softlimit), "warn")
173            (softlimit, hardlimit) = (hardlimit, softlimit)
174        for printer in printernames :
175            if options["prototype"] :
176                if options["users"] :
177                    prototype = self.storage.getUserPQuota(options["prototype"], printer)
178                else :     
179                    prototype = self.storage.getGroupPQuota(options["prototype"], printer)
180                if prototype is None :
181                    self.logger.log_message("Prototype %s not found in Quota Storage for printer %s." % (options["prototype"], printer))
182                    continue    # skip this printer
183                else :   
184                    (softlimit, hardlimit) = (prototype["softlimit"], prototype["hardlimit"])
185            if hardlimit is None :   
186                hardlimit = softlimit
187                self.logger.log_message("Undefined hard limit set to soft limit (%s) on printer %s." % (str(hardlimit), printer))
188            if softlimit is None :   
189                softlimit = hardlimit
190                self.logger.log_message("Undefined soft limit set to hard limit (%s) on printer %s." % (str(softlimit), printer))
191            if (hardlimit is None) or (softlimit is None) :       
192                raise PyKotaToolError, "Both hard and soft limits must be set ! Aborting."
193            for name in names :
194                if options["users"] :
195                    quota = self.storage.getUserPQuota(name, printer)
196                else :
197                    quota = self.storage.getGroupPQuota(name, printer)
198                if quota is None :
199                    # not found
200                    if options["add"] :
201                        if options["users"] :
202                            self.storage.addUserPQuota(name, printer)
203                            quota = self.storage.getUserPQuota(name, printer)
204                        else :
205                            self.storage.addGroupPQuota(name, printer)
206                            quota = self.storage.getGroupPQuota(name, printer)
207                if quota is None :     
208                    self.logger.log_message("Quota not found for object %s on printer %s." % (name, printer))
209                else :   
210                    if options["users"] :
211                        self.storage.setUserPQuota(name, printer, softlimit, hardlimit)
212                    else :
213                        self.storage.setGroupPQuota(name, printer, softlimit, hardlimit)
214                     
215if __name__ == "__main__" : 
216    try :
217        defaults = { \
218                     "users"  : 1, \
219                     "groups" : 0, \
220                     "printer" : "*", \
221                   }
222        short_options = "vhaugp:P:S:H:"
223        long_options = ["help", "version", "add", "users", "groups", "prototype=", "printer=", "softlimit=", "hardlimit="]
224       
225        # Initializes the command line tool
226        editor = EdPyKota(doc=__doc__)
227       
228        # parse and checks the command line
229        (options, args) = editor.parseCommandline(sys.argv[1:], short_options, long_options)
230       
231        # sets long options
232        options["help"] = options["h"] or options["help"]
233        options["version"] = options["v"] or options["version"]
234        options["add"] = options["a"] or options["add"]
235        options["users"] = options["u"] or options["users"] or defaults["users"]
236        options["groups"] = options["g"] or options["groups"] or defaults["groups"]
237        options["prototype"] = options["p"] or options["prototype"]
238        options["printer"] = options["P"] or options["printer"] or defaults["printer"]
239        options["softlimit"] = options["S"] or options["softlimit"]
240        options["hardlimit"] = options["H"] or options["hardlimit"] 
241       
242        if options["help"] :
243            editor.display_usage_and_quit()
244        elif options["version"] :
245            editor.display_version_and_quit()
246        elif options["users"] and options["groups"] :   
247            raise PyKotaToolError, "edpykota: options --users and --groups are incompatible."
248        elif (options["softlimit"] or options["hardlimit"]) and options["prototype"] :   
249            raise PyKotaToolError, "edpykota: options --softlimit or --hardlimit and --prototype are incompatible."
250        elif options["groups"] :   
251            raise PyKotaToolError, "edpykota: options --groups is currently not implemented."
252        else :
253            sys.exit(editor.main(args, options))
254    except PyKotaToolError, msg :           
255        sys.stderr.write("%s\n" % msg)
256        sys.stderr.flush()
257        sys.exit(-1)
Note: See TracBrowser for help on using the browser.