root / pykota / trunk / bin / edpykota @ 1956

Revision 1956, 31.9 kB (checked in by jalet, 19 years ago)

Added the reject_unknown directive to pykota.conf to reject user/group
creation if user or group is unknown to the system

  • 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: ISO-8859-15 -*-
3
4# PyKota Print Quota Editor
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program; if not, write to the Free Software
21# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22#
23# $Id$
24#
25# $Log$
26# Revision 1.82  2004/11/22 21:53:38  jalet
27# Added the reject_unknown directive to pykota.conf to reject user/group
28# creation if user or group is unknown to the system
29#
30# Revision 1.81  2004/10/12 15:37:00  jalet
31# Now outputs the name of the offending user if a mere mortal tries to use
32# one of these commands !!!
33#
34# Revision 1.80  2004/10/11 22:53:05  jalet
35# Postponed string interpolation to help message's output method
36#
37# Revision 1.79  2004/10/11 12:49:06  jalet
38# Renders help translatable
39#
40# Revision 1.78  2004/10/07 14:35:40  jalet
41# Now edpykota refuses to launch if the user is not a PyKota administrator.
42# dumpykota : now has the same error message than edpykota in this case.
43#
44# Revision 1.77  2004/09/28 17:45:31  jalet
45# Added the --hardreset command line option to edpykota
46#
47# Revision 1.76  2004/07/01 19:56:40  jalet
48# Better dispatching of error messages
49#
50# Revision 1.75  2004/06/18 13:34:47  jalet
51# Now all tracebacks include PyKota's version number
52#
53# Revision 1.74  2004/06/07 18:43:40  jalet
54# Fixed over-verbose exits when displaying help or version number
55#
56# Revision 1.73  2004/06/03 21:50:34  jalet
57# Improved error logging.
58# crashrecipient directive added.
59# Now exports the job's size in bytes too.
60#
61# Revision 1.72  2004/04/16 16:20:19  jalet
62# Note about not implemented limitby values
63#
64# Revision 1.71  2004/03/24 15:15:24  jalet
65# Began integration of Henrik Janhagen's work on quota-then-balance
66# and balance-then-quota
67#
68# Revision 1.70  2004/02/27 09:23:21  jalet
69# Minor code reorganisation
70#
71# Revision 1.69  2004/02/19 15:05:56  jalet
72# domain names changed to example.com in the doc, according to RFC2606
73#
74# Revision 1.68  2004/01/28 10:05:22  jalet
75# New user/group deletion code
76#
77# Revision 1.67  2004/01/15 11:19:07  jalet
78# Typos in messages wrt gettext.
79#
80# Revision 1.66  2004/01/12 21:54:36  jalet
81# User's email address can now be set at user's creation time.
82#
83# Revision 1.65  2004/01/08 16:24:49  jalet
84# edpykota now supports adding printers to printer groups.
85#
86# Revision 1.64  2004/01/08 14:10:32  jalet
87# Copyright year changed.
88#
89# Revision 1.63  2003/11/24 16:50:58  jalet
90# Old help message deletedd
91#
92# Revision 1.62  2003/11/12 23:28:38  jalet
93# More work on new backend. This commit may be unstable.
94#
95# Revision 1.61  2003/11/12 13:06:35  jalet
96# Bug fix wrt no user/group name command line argument to edpykota
97#
98# Revision 1.60  2003/10/09 21:25:24  jalet
99# Multiple printer names or wildcards can be passed on the command line
100# separated with commas.
101# Beta phase.
102#
103# Revision 1.59  2003/10/07 09:07:27  jalet
104# Character encoding added to please latest version of Python
105#
106# Revision 1.58  2003/10/03 12:27:01  jalet
107# Several optimizations, especially with LDAP backend
108#
109# Revision 1.57  2003/08/20 16:01:19  jalet
110# Comment added.
111#
112# Revision 1.56  2003/07/29 20:55:17  jalet
113# 1.14 is out !
114#
115# Revision 1.55  2003/07/28 09:11:12  jalet
116# PyKota now tries to add its attributes intelligently in existing LDAP
117# directories.
118#
119# Revision 1.54  2003/07/21 06:32:42  jalet
120# Prevents email messages to be sent at modification/creation time for
121# a user/group quota
122#
123# Revision 1.53  2003/07/09 06:03:41  jalet
124# Fixed typo when using edpykota --prototype
125#
126# Revision 1.52  2003/07/07 12:11:13  jalet
127# Small fix
128#
129# Revision 1.51  2003/07/07 11:55:50  jalet
130# Small fix
131#
132# Revision 1.50  2003/07/05 12:33:53  jalet
133# More on previous fix.
134#
135# Revision 1.49  2003/07/05 12:32:07  jalet
136# Ensure that the user don't pass more than two prices for a printer.
137#
138# Revision 1.48  2003/06/25 19:52:30  jalet
139# Should be ready for testing :-)
140#
141# Revision 1.47  2003/06/25 14:10:01  jalet
142# Hey, it may work (edpykota --reset excepted) !
143#
144# Revision 1.46  2003/06/16 11:59:09  jalet
145# More work on LDAP
146#
147# Revision 1.45  2003/06/11 19:32:00  jalet
148# Severe bug wrt account balance setting should be corrected.
149#
150# Revision 1.44  2003/04/29 22:03:38  jalet
151# Better error handling.
152#
153# Revision 1.43  2003/04/23 22:13:56  jalet
154# Preliminary support for LPRng added BUT STILL UNTESTED.
155#
156# Revision 1.42  2003/04/17 13:38:47  jalet
157# Docstring corrected for better manual page
158#
159# Revision 1.41  2003/04/16 12:35:49  jalet
160# Groups quota work now !
161#
162# Revision 1.40  2003/04/16 08:22:09  jalet
163# More strict error detection.
164# Minor code rewrite to avoid some repetitive tests.
165#
166# Revision 1.39  2003/04/16 08:01:53  jalet
167# edpykota --charge command line option works now.
168#
169# Revision 1.38  2003/04/15 22:02:43  jalet
170# More complete docstring
171#
172# Revision 1.37  2003/04/15 21:58:33  jalet
173# edpykota now accepts a --delete option.
174# Preparation to allow edpykota to accept much more command line options
175# (WARNING : docstring is OK, but code isn't !)
176#
177# Revision 1.36  2003/04/15 13:55:28  jalet
178# Options --limitby and --balance added to edpykota
179#
180# Revision 1.35  2003/04/15 13:06:39  jalet
181# Allow to add a printer without any user
182#
183# Revision 1.34  2003/04/11 16:51:11  jalet
184# Bug fix for edpykota --add with users who already had a quota on the printer.
185#
186# Revision 1.33  2003/04/10 21:47:20  jalet
187# Job history added. Upgrade script neutralized for now !
188#
189# Revision 1.32  2003/04/08 21:31:39  jalet
190# (anything or 0) = anything !!! Go back to school Jerome !
191#
192# Revision 1.31  2003/04/08 21:13:44  jalet
193# Prepare --groups option to work.
194#
195# Revision 1.30  2003/04/08 21:10:18  jalet
196# Checks --groups option presence instead of --users because --users is the default.
197#
198# Revision 1.29  2003/04/05 09:28:56  jalet
199# Unnecessary message was logged
200#
201# Revision 1.28  2003/03/29 13:45:26  jalet
202# GPL paragraphs were incorrectly (from memory) copied into the sources.
203# Two README files were added.
204# Upgrade script for PostgreSQL pre 1.01 schema was added.
205#
206# Revision 1.27  2003/03/10 00:23:04  jalet
207# Bad english
208#
209# Revision 1.26  2003/03/10 00:11:27  jalet
210# Cleaner example.
211#
212# Revision 1.25  2003/03/09 23:56:21  jalet
213# Option noquota added to do accounting only.
214#
215# Revision 1.24  2003/02/27 23:48:41  jalet
216# Correctly maps PyKota's log levels to syslog log levels
217#
218# Revision 1.23  2003/02/27 22:55:20  jalet
219# WARN log priority doesn't exist.
220#
221# Revision 1.22  2003/02/27 09:37:02  jalet
222# Wildcards seem to work now
223#
224# Revision 1.21  2003/02/27 09:04:46  jalet
225# user and group names can be passed as wildcards if the --add option
226# is not set. The default is to act on all users or groups.
227#
228# Revision 1.20  2003/02/10 12:07:30  jalet
229# Now repykota should output the recorded total page number for each printer too.
230#
231# Revision 1.19  2003/02/09 13:40:29  jalet
232# typo
233#
234# Revision 1.18  2003/02/09 12:56:53  jalet
235# Internationalization begins...
236#
237# Revision 1.17  2003/02/08 22:47:23  jalet
238# Option --reset can now be used without having to use soft and hard limits
239# on the command line.
240#
241# Revision 1.16  2003/02/08 22:39:46  jalet
242# --reset command line option added
243#
244# Revision 1.15  2003/02/08 22:20:01  jalet
245# Clarification on why we don't check with /etc/passwd to see if the user
246# name is valid or not.
247#
248# Revision 1.14  2003/02/08 22:18:15  jalet
249# Now checks user and group names for validity before adding them
250#
251# Revision 1.13  2003/02/08 22:09:02  jalet
252# Only printer was added the first time.
253#
254# Revision 1.12  2003/02/08 21:44:49  jalet
255# Python 2.1 string module doesn't define ascii_letters
256#
257# Revision 1.11  2003/02/08 09:42:44  jalet
258# Better handle wrong or bad command line arguments
259#
260# Revision 1.10  2003/02/08 09:39:20  jalet
261# typos
262#
263# Revision 1.9  2003/02/08 09:38:06  jalet
264# Badly placed test
265#
266# Revision 1.8  2003/02/07 22:53:57  jalet
267# Checks if printer name is valid before adding it
268#
269# Revision 1.7  2003/02/07 22:17:58  jalet
270# Incomplete test
271#
272# Revision 1.6  2003/02/07 22:13:13  jalet
273# Perhaps edpykota is now able to add printers !!! Oh, stupid me !
274#
275# Revision 1.5  2003/02/06 14:49:04  jalet
276# edpykota should be ok now
277#
278# Revision 1.4  2003/02/06 14:28:59  jalet
279# edpykota should be ok, minus some typos
280#
281# Revision 1.3  2003/02/06 10:47:21  jalet
282# Documentation string and command line options didn't match.
283#
284# Revision 1.2  2003/02/06 10:39:23  jalet
285# Preliminary edpykota work.
286#
287# Revision 1.1  2003/02/05 21:41:09  jalet
288# Skeletons added for all command line tools
289#
290#
291#
292
293import sys
294import os
295import pwd
296import grp
297from pykota.tool import PyKotaTool, PyKotaToolError, crashed, N_
298from pykota.config import PyKotaConfigError
299from pykota.storage import PyKotaStorageError
300
301__doc__ = N_("""edpykota v%s (c) 2003-2004 C@LL - Conseil Internet & Logiciels Libres
302A Print Quota editor for PyKota.
303
304command line usage :
305
306  edpykota [options] user1 user2 ... userN
307 
308  edpykota [options] group1 group2 ... groupN
309
310options :
311
312  -v | --version       Prints edpykota's version number then exits.
313  -h | --help          Prints this message then exits.
314 
315  -a | --add           Adds users and/or printers if they don't
316                       exist on the Quota Storage Server.
317                       
318  -d | --delete        Deletes users/groups from the quota storage.
319                       Printers are never deleted.
320                       
321  -c | --charge p[,j]  Sets the price per page and per job to charge
322                       for a particular printer. Job price is optional.
323                       If both are to be set, separate them with a comma.
324                       Floating point values are allowed.
325 
326  -i | --ingroups g1[,g2...]  Puts the users into each of the groups
327                              listed, separated by commas. The groups
328                              must already exist in the Quota Storage.
329 
330  -u | --users         Edit users print quotas, this is the default.
331 
332  -P | --printer p     Edit quotas on printer p only. Actually p can
333                       use wildcards characters to select only
334                       some printers. The default value is *, meaning
335                       all printers.
336                       You can specify several names or wildcards,
337                       by separating them with commas.
338 
339  -G | --pgroups pg1[,pg2...] Adds the printer(s) to the printer groups
340                       pg1, pg2, etc... which must already exist.
341                       A printer group is just like a normal printer,
342                       only that it is usually unknown from the printing
343                       system. Create printer groups exactly the same
344                       way that you create printers, then add other
345                       printers to them with this option.
346                       Accounting is done on a printer and on all
347                       the printer groups it belongs to, quota checking
348                       is done on a printer and on all the printer groups
349                       it belongs to.
350 
351  -g | --groups        Edit users groups print quotas instead of users.
352                         
353  -p | --prototype u|g Uses user u or group g as a prototype to set
354                       print quotas
355                       
356  -n | --noquota       Doesn't set a quota but only does accounting.
357 
358  -r | --reset         Resets the actual page counter for the user
359                       or group to zero on the specified printers.
360                       The life time page counter is kept unchanged.
361                       
362  -R | --hardreset     Resets the actual and life time page counters
363                       for the user or group to zero on the specified
364                       printers.
365                       
366  -l | --limitby l     Choose if the user/group is limited in printing                     
367                       by its account balance or by its page quota.
368                       The default value is 'quota'. Allowed values
369                       are 'quota' 'balance' 'quota-then-balance' and
370                       'balance-then-quota'.
371                       WARNING : quota-then-balance and balance-then-quota
372                       are not yet implemented.
373                       
374  -b | --balance b     Sets the user's account balance to b.                     
375                       Account balance may be increase or decreased
376                       if b is prefixed with + or -.
377                       WARNING : when decreasing account balance,
378                       the total paid so far by the user is decreased
379                       too.
380                       Groups don't have a real balance, but the
381                       sum of their users' account balance.
382                       
383  -S | --softlimit sl  Sets the quota soft limit to sl pages.                       
384 
385  -H | --hardlimit hl  Sets the quota hard limit to hl pages.
386 
387  user1 through userN and group1 through groupN can use wildcards
388  if the --add option is not set.
389 
390examples :                             
391
392  $ edpykota --add -p jerome john paul george ringo/ringo@example.com
393 
394  This will add users john, paul, george and ringo to the quota
395  database, and set their print quotas to the same values than user
396  jerome. User jerome must already exist.
397  User ringo's email address will also be set to 'ringo@example.com'
398 
399  $ edpykota --printer lp -S 50 -H 60 jerome
400 
401  This will set jerome's print quota on the lp printer to a soft limit
402  of 50 pages, and a hard limit of 60 pages. If either user jerome or
403  printer lp doesn't exist on the Quota Storage Server then nothing is done.
404
405  $ edpykota --add --printer lp --ingroups coders,it -S 50 -H 60 jerome
406 
407  Same as above, but if either user jerome or printer lp doesn't exist
408  on the Quota Storage Server they are automatically added. Also
409  user jerome is put into the groups "coders" and "it" which must
410  already exist in the Quota Storage.
411           
412  $ edpykota -g -S 500 -H 550 financial support           
413 
414  This will set print quota soft limit to 500 pages and hard limit
415  to 550 pages for groups financial and support on all printers.
416 
417  $ edpykota --reset jerome "jo*"
418 
419  This will reset jerome's page counter to zero on all printers, as
420  well as every user whose name begins with 'jo'.
421  Their life time page counter on each printer will be kept unchanged.
422  You can also reset the life time page counters by using the
423  --hardreset | -R command line option.
424 
425  $ edpykota --printer hpcolor --noquota jerome
426 
427  This will tell PyKota to not limit jerome when printing on the
428  hpcolor printer. All his jobs will be allowed on this printer, but
429  accounting of the pages he prints will still be kept.
430  Print Quotas for jerome on other printers are unchanged.
431 
432  $ edpykota --limitby balance jerome
433 
434  This will tell PyKota to limit jerome by his account's balance
435  when printing.
436 
437  $ edpykota --balance +10.0 jerome
438 
439  This will increase jerome's account balance by 10.0 (in your
440  own currency). You can decrease the account balance with a
441  dash prefix, and set it to a fixed amount with no prefix.
442 
443  $ edpykota --delete jerome rachel
444 
445  This will completely delete jerome and rachel from the Quota Storage
446  database. All their quotas and jobs will be deleted too.
447 
448  $ edpykota --printer lp --charge 0.1
449 
450  This will set the page price for printer lp to 0.1. Job price
451  will not be changed.
452 
453  $ edpykota --printer hplj1,hplj2 --pgroups Laser,HP
454 
455  This will put printers hplj1 and hplj2 in printers groups Laser and HP.
456  When printing either on hplj1 or hplj2, print quota will also be
457  checked and accounted for on virtual printers Laser and HP.
458
459This program is free software; you can redistribute it and/or modify
460it under the terms of the GNU General Public License as published by
461the Free Software Foundation; either version 2 of the License, or
462(at your option) any later version.
463
464This program is distributed in the hope that it will be useful,
465but WITHOUT ANY WARRANTY; without even the implied warranty of
466MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
467GNU General Public License for more details.
468
469You should have received a copy of the GNU General Public License
470along with this program; if not, write to the Free Software
471Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
472
473Please e-mail bugs to: %s""") 
474       
475class EdPyKota(PyKotaTool) :       
476    """A class for edpykota."""
477    def main(self, names, options) :
478        """Edit user or group quotas."""
479        if not self.config.isAdmin :
480            raise PyKotaToolError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
481       
482        suffix = (options["groups"] and "Group") or "User"       
483       
484        softlimit = hardlimit = None   
485        if not options["noquota"] :
486            if options["softlimit"] :
487                try :
488                    softlimit = int(options["softlimit"].strip())
489                except ValueError :   
490                    raise PyKotaToolError, _("Invalid softlimit value %s.") % options["softlimit"]
491            if options["hardlimit"] :
492                try :
493                    hardlimit = int(options["hardlimit"].strip())
494                except ValueError :   
495                    raise PyKotaToolError, _("Invalid hardlimit value %s.") % options["hardlimit"]
496            if (softlimit is not None) and (hardlimit is not None) and (hardlimit < softlimit) :       
497                # error, exchange them
498                self.printInfo(_("Hard limit %i is less than soft limit %i, values will be exchanged.") % (hardlimit, softlimit))
499                (softlimit, hardlimit) = (hardlimit, softlimit)
500           
501        balance = options["balance"]
502        if balance :
503            balance = balance.strip()
504            try :
505                balancevalue = float(balance)
506            except ValueError :   
507                raise PyKotaToolError, _("Invalid balance value %s") % options["balance"]
508           
509        if options["charge"] :
510            try :
511                charges = [float(part) for part in options["charge"].split(',', 1)]
512            except ValueError :   
513                raise PyKotaToolError, _("Invalid charge amount value %s") % options["charge"]
514            else :   
515                if len(charges) > 2 :
516                    charges = charges[:2]
517                if len(charges) != 2 :
518                    charges = [charges[0], None]
519                   
520        limitby = options["limitby"]
521        if limitby :
522            limitby = limitby.strip().lower()
523        if limitby and (limitby not in ('quota', 'balance', 'quota-then-balance', 'balance-then-quota')) :   
524            raise PyKotaToolError, _("Invalid limitby value %s") % options["limitby"]
525           
526        if options["ingroups"] :   
527            groupnames = [gname.strip() for gname in options["ingroups"].split(',')]
528        else :   
529            groupnames = []
530           
531        if options["prototype"] :   
532            protoentry = getattr(self.storage, "get%s" % suffix)(options["prototype"])
533           
534        rejectunknown = self.config.getRejectUnknown()   
535        printeradded = 0
536        printers = self.storage.getMatchingPrinters(options["printer"])
537        if not printers :
538            pname = options["printer"]
539            if options["add"] and pname :
540                if self.isValidName(pname) :
541                    printers = [ self.storage.addPrinter(pname) ]
542                    if printers[0].Exists :
543                        printeradded = 1
544                    else :   
545                        raise PyKotaToolError, _("Impossible to add printer %s") % pname
546                else :   
547                    raise PyKotaToolError, _("Invalid printer name %s") % pname
548            else :
549                raise PyKotaToolError, _("There's no printer matching %s") % pname
550        if not names :   
551            if options["add"] :
552                if not printeradded :
553                    raise PyKotaToolError, _("You have to pass user or group names on the command line")
554                else :   
555                    names = getattr(self.storage, "getAll%ssNames" % suffix)()
556            else :   
557                names = [ "*" ] # all users
558               
559        printersgroups = []       
560        if options["pgroups"] :       
561            printersgroups = self.storage.getMatchingPrinters(options["pgroups"])
562           
563        todelete = {}   
564        changed = {} # tracks changes made at the user/group level
565        for printer in printers :
566            for pgroup in printersgroups :
567                pgroup.addPrinterToGroup(printer)   
568               
569            if options["charge"] :
570                (perpage, perjob) = charges
571                printer.setPrices(perpage, perjob)   
572               
573            if options["prototype"] :
574                if protoentry.Exists :
575                    protoquota = getattr(self.storage, "get%sPQuota" % suffix)(protoentry, printer)
576                    if not protoquota.Exists :
577                        self.printInfo(_("Prototype %s not found in Quota Storage for printer %s.") % (protoentry.Name, printer.Name))
578                        continue    # skip this printer
579                    else :   
580                        (softlimit, hardlimit) = (protoquota.SoftLimit, protoquota.HardLimit)
581                else :       
582                    self.printInfo(_("Prototype object %s not found in Quota Storage.") % protoentry.Name)
583                   
584            if not options["noquota"] :   
585                if hardlimit is None :   
586                    hardlimit = softlimit
587                    if hardlimit is not None :
588                        self.printInfo(_("Undefined hard limit set to soft limit (%s) on printer %s.") % (str(hardlimit), printer.Name))
589                if softlimit is None :   
590                    softlimit = hardlimit
591                    if softlimit is not None :
592                        self.printInfo(_("Undefined soft limit set to hard limit (%s) on printer %s.") % (str(softlimit), printer.Name))
593                       
594            if options["add"] :   
595                allentries = []   
596                for name in names :
597                    email = ""
598                    if not options["groups"] :
599                        splitname = name.split('/', 1)     # username/email
600                        if len(splitname) == 1 :
601                            splitname.append("")
602                        (name, email) = splitname
603                        if email and (email.count('@') != 1) :
604                            self.printInfo(_("Invalid email address %s") % email)
605                            email = ""
606                    entry = getattr(self.storage, "get%s" % suffix)(name)
607                    if email and not options["groups"] :
608                        entry.Email = email
609                    entrypquota = getattr(self.storage, "get%sPQuota" % suffix)(entry, printer)
610                    allentries.append((entry, entrypquota))
611            else :   
612                allentries = getattr(self.storage, "getPrinter%ssAndQuotas" % suffix)(printer, names)
613               
614            for (entry, entrypquota) in allentries :
615                if not changed.has_key(entry.Name) :
616                    changed[entry.Name] = {}
617                    if not options["groups"] :
618                        changed[entry.Name]["ingroups"] = []
619                       
620                if not entry.Exists :       
621                    # not found
622                    if options["add"] :
623                        # In case we want to add something, it is crucial
624                        # that we DON'T check with the system accounts files
625                        # like /etc/passwd because users may be defined
626                        # only remotely
627                        if self.isValidName(entry.Name) :
628                            reject = 0
629                            if rejectunknown :
630                                if options["groups"] :
631                                    try :
632                                        grp.getgrnam(entry.Name)
633                                    except KeyError :   
634                                        self.printInfo(_("Unknown group %s") % entry.Name, "error")
635                                        reject = 1
636                                else :   
637                                    try :
638                                        pwd.getpwnam(entry.Name)
639                                    except KeyError :   
640                                        self.printInfo(_("Unknown user %s") % entry.Name, "error")
641                                        reject = 1
642                            if not reject :       
643                                entry = getattr(self.storage, "add%s" % suffix)(entry)
644                        else :   
645                            if options["groups"] :
646                                self.printInfo(_("Invalid group name %s") % entry.Name)
647                            else :   
648                                self.printInfo(_("Invalid user name %s") % entry.Name)
649                elif options["delete"] :               
650                    todelete[entry.Name] = entry
651                               
652                if entry.Exists and (not entrypquota.Exists) :
653                    # not found
654                    if options["add"] :
655                        entrypquota = getattr(self.storage, "add%sPQuota" % suffix)(entry, printer)
656                       
657                if not entrypquota.Exists :     
658                    self.printInfo(_("Quota not found for object %s on printer %s.") % (entry.Name, printer.Name))
659                else :   
660                    if options["noquota"] or options["prototype"] or ((softlimit is not None) and (hardlimit is not None)) :
661                        entrypquota.setLimits(softlimit, hardlimit)
662                    if limitby :
663                        if changed[entry.Name].get("limitby") is None :
664                            entry.setLimitBy(limitby)
665                            changed[entry.Name]["limitby"] = limitby
666                   
667                    if not options["groups"] :
668                        if options["reset"] :
669                            entrypquota.reset()
670                        elif options["hardreset"] :   
671                            entrypquota.hardreset()
672                           
673                        if balance :
674                            if changed[entry.Name].get("balance") is None :
675                                if balance.startswith("+") or balance.startswith("-") :
676                                    newbalance = float(entry.AccountBalance or 0.0) + balancevalue
677                                    newlifetimepaid = float(entry.LifeTimePaid or 0.0) + balancevalue
678                                    entry.setAccountBalance(newbalance, newlifetimepaid)
679                                else :
680                                    diff = balancevalue - float(entry.AccountBalance or 0.0)
681                                    newlifetimepaid = float(entry.LifeTimePaid or 0.0) + diff
682                                    entry.setAccountBalance(balancevalue, newlifetimepaid)
683                                changed[entry.Name]["balance"] = balance
684                               
685                        for groupname in groupnames :       
686                            # not executed if option --ingroups is not used
687                            if groupname not in changed[entry.Name]["ingroups"] :
688                                group = self.storage.getGroup(groupname)
689                                if group.Exists :
690                                    self.storage.addUserToGroup(entry, group)
691                                    changed[entry.Name]["ingroups"].append(groupname)
692                                else :
693                                    self.printInfo(_("Group %s not found in the PyKota Storage.") % groupname)
694                                   
695                    # This line disabled to prevent sending of unwanted email                 
696                    # messages if quota is reached at creation/modification time.
697                    # The check will be done at print time anyway.
698                    # getattr(self, "warn%sPQuota" % suffix)(entrypquota)   
699                       
700        # Now delete what has to be deleted               
701        for (name, entry) in todelete.items() :               
702            entry.delete()
703                     
704if __name__ == "__main__" : 
705    retcode = 0
706    try :
707        defaults = { \
708                     "printer" : "*", \
709                   }
710        short_options = "vhdc:l:b:i:naugrp:P:S:H:G:R"
711        long_options = ["help", "version", "charge=", "delete", "limitby=", "balance=", "ingroups=", "noquota", "add", "users", "groups", "reset", "hardreset", "prototype=", "printer=", "softlimit=", "hardlimit=", "pgroups="]
712       
713        # Initializes the command line tool
714        editor = EdPyKota(doc=__doc__)
715       
716        # parse and checks the command line
717        (options, args) = editor.parseCommandline(sys.argv[1:], short_options, long_options)
718       
719        # sets long options
720        options["help"] = options["h"] or options["help"]
721        options["version"] = options["v"] or options["version"]
722        options["add"] = options["a"] or options["add"]
723        options["users"] = options["u"] or options["users"]
724        options["groups"] = options["g"] or options["groups"]
725        options["prototype"] = options["p"] or options["prototype"]
726        options["printer"] = options["P"] or options["printer"] or defaults["printer"]
727        options["softlimit"] = options["S"] or options["softlimit"]
728        options["hardlimit"] = options["H"] or options["hardlimit"] 
729        options["reset"] = options["r"] or options["reset"] 
730        options["noquota"] = options["n"] or options["noquota"]
731        options["limitby"] = options["l"] or options["limitby"]
732        options["balance"] = options["b"] or options["balance"] 
733        options["delete"] = options["d"] or options["delete"] 
734        options["ingroups"] = options["i"] or options["ingroups"]
735        options["charge"] = options["c"] or options["charge"]
736        options["pgroups"] = options["G"] or options["pgroups"]
737        options["hardreset"] = options["R"] or options["hardreset"] 
738       
739        if options["help"] :
740            editor.display_usage_and_quit()
741        elif options["version"] :
742            editor.display_version_and_quit()
743        elif options["users"] and options["groups"] :   
744            raise PyKotaToolError, _("incompatible options, see help.")
745        elif (options["add"] or options["prototype"]) and options["delete"] :   
746            raise PyKotaToolError, _("incompatible options, see help.")
747        elif (options["softlimit"] or options["hardlimit"]) and options["prototype"] :   
748            raise PyKotaToolError, _("incompatible options, see help.")
749        elif options["noquota"] and (options["prototype"] or options["hardlimit"] or options["softlimit"]) :
750            raise PyKotaToolError, _("incompatible options, see help.")
751        elif options["groups"] and (options["balance"] or options["ingroups"]) :
752            raise PyKotaToolError, _("incompatible options, see help.")
753        else :
754            retcode = editor.main(args, options)
755    except SystemExit :       
756        pass
757    except :
758        try :
759            editor.crashed("edpykota failed")
760        except :   
761            crashed("edpykota failed")
762        retcode = -1
763
764    try :
765        editor.storage.close()
766    except (TypeError, NameError, AttributeError) :   
767        pass
768       
769    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.