]> git.decadent.org.uk Git - dak.git/blob - dak/rm.py
Actualy close bugs associated to removed packaged on request
[dak.git] / dak / rm.py
1 #!/usr/bin/env python
2
3 """ General purpose package removal tool for ftpmaster """
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006  James Troup <james@nocrew.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 ################################################################################
21
22 # o OpenBSD team wants to get changes incorporated into IPF. Darren no
23 #    respond.
24 # o Ask again -> No respond. Darren coder supreme.
25 # o OpenBSD decide to make changes, but only in OpenBSD source
26 #    tree. Darren hears, gets angry! Decides: "LICENSE NO ALLOW!"
27 # o Insert Flame War.
28 # o OpenBSD team decide to switch to different packet filter under BSD
29 #    license. Because Project Goal: Every user should be able to make
30 #    changes to source tree. IPF license bad!!
31 # o Darren try get back: says, NetBSD, FreeBSD allowed! MUAHAHAHAH!!!
32 # o Theo say: no care, pf much better than ipf!
33 # o Darren changes mind: changes license. But OpenBSD will not change
34 #    back to ipf. Darren even much more bitter.
35 # o Darren so bitterbitter. Decides: I'LL GET BACK BY FORKING OPENBSD AND
36 #    RELEASING MY OWN VERSION. HEHEHEHEHE.
37
38 #                        http://slashdot.org/comments.pl?sid=26697&cid=2883271
39
40 ################################################################################
41
42 import commands
43 import os
44 import sys
45 import apt_pkg
46 import apt_inst
47 from re import sub
48
49 from daklib.config import Config
50 from daklib.dbconn import *
51 from daklib import utils
52 from daklib.dak_exceptions import *
53 from daklib.regexes import re_strip_source_version, re_build_dep_arch
54
55 ################################################################################
56
57 Options = None
58
59 ################################################################################
60
61 def usage (exit_code=0):
62     print """Usage: dak rm [OPTIONS] PACKAGE[...]
63 Remove PACKAGE(s) from suite(s).
64
65   -a, --architecture=ARCH    only act on this architecture
66   -b, --binary               remove binaries only
67   -c, --component=COMPONENT  act on this component
68   -C, --carbon-copy=EMAIL    send a CC of removal message to EMAIL
69   -d, --done=BUG#            send removal message as closure to bug#
70   -D, --do-close             also close all bugs associated to that package
71   -h, --help                 show this help and exit
72   -m, --reason=MSG           reason for removal
73   -n, --no-action            don't do anything
74   -p, --partial              don't affect override files
75   -R, --rdep-check           check reverse dependencies
76   -s, --suite=SUITE          act on this suite
77   -S, --source-only          remove source only
78
79 ARCH, BUG#, COMPONENT and SUITE can be comma (or space) separated lists, e.g.
80     --architecture=amd64,i386"""
81
82     sys.exit(exit_code)
83
84 ################################################################################
85
86 # "Hudson: What that's great, that's just fucking great man, now what
87 #  the fuck are we supposed to do? We're in some real pretty shit now
88 #  man...That's it man, game over man, game over, man! Game over! What
89 #  the fuck are we gonna do now? What are we gonna do?"
90
91 def game_over():
92     answer = utils.our_raw_input("Continue (y/N)? ").lower()
93     if answer != "y":
94         print "Aborted."
95         sys.exit(1)
96
97 ################################################################################
98
99 def reverse_depends_check(removals, suites, arches=None):
100     cnf = Config()
101
102     print "Checking reverse dependencies..."
103     components = cnf.ValueList("Suite::%s::Components" % suites[0])
104     dep_problem = 0
105     p2c = {}
106     all_broken = {}
107     if arches:
108         all_arches = set(arches)
109     else:
110         all_arches = set([x.arch_string for x in get_suite_architectures(suites[0])])
111     all_arches -= set(["source", "all"])
112     for architecture in all_arches:
113         deps = {}
114         sources = {}
115         virtual_packages = {}
116         for component in components:
117             filename = "%s/dists/%s/%s/binary-%s/Packages.gz" % (cnf["Dir::Root"], suites[0], component, architecture)
118             # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
119             (fd, temp_filename) = utils.temp_filename()
120             (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
121             if (result != 0):
122                 utils.fubar("Gunzip invocation failed!\n%s\n" % (output), result)
123             # Also check for udebs
124             filename = "%s/dists/%s/%s/debian-installer/binary-%s/Packages.gz" % (cnf["Dir::Root"], suites[0], component, architecture)
125             if os.path.exists(filename):
126                 (result, output) = commands.getstatusoutput("gunzip -c %s >> %s" % (filename, temp_filename))
127                 if (result != 0):
128                     utils.fubar("Gunzip invocation failed!\n%s\n" % (output), result)
129             packages = utils.open_file(temp_filename)
130             Packages = apt_pkg.ParseTagFile(packages)
131             while Packages.Step():
132                 package = Packages.Section.Find("Package")
133                 source = Packages.Section.Find("Source")
134                 if not source:
135                     source = package
136                 elif ' ' in source:
137                     source = source.split(' ', 1)[0]
138                 sources[package] = source
139                 depends = Packages.Section.Find("Depends")
140                 if depends:
141                     deps[package] = depends
142                 provides = Packages.Section.Find("Provides")
143                 # Maintain a counter for each virtual package.  If a
144                 # Provides: exists, set the counter to 0 and count all
145                 # provides by a package not in the list for removal.
146                 # If the counter stays 0 at the end, we know that only
147                 # the to-be-removed packages provided this virtual
148                 # package.
149                 if provides:
150                     for virtual_pkg in provides.split(","):
151                         virtual_pkg = virtual_pkg.strip()
152                         if virtual_pkg == package: continue
153                         if not virtual_packages.has_key(virtual_pkg):
154                             virtual_packages[virtual_pkg] = 0
155                         if package not in removals:
156                             virtual_packages[virtual_pkg] += 1
157                 p2c[package] = component
158             packages.close()
159             os.unlink(temp_filename)
160
161         # If a virtual package is only provided by the to-be-removed
162         # packages, treat the virtual package as to-be-removed too.
163         for virtual_pkg in virtual_packages.keys():
164             if virtual_packages[virtual_pkg] == 0:
165                 removals.append(virtual_pkg)
166
167         # Check binary dependencies (Depends)
168         for package in deps.keys():
169             if package in removals: continue
170             parsed_dep = []
171             try:
172                 parsed_dep += apt_pkg.ParseDepends(deps[package])
173             except ValueError, e:
174                 print "Error for package %s: %s" % (package, e)
175             for dep in parsed_dep:
176                 # Check for partial breakage.  If a package has a ORed
177                 # dependency, there is only a dependency problem if all
178                 # packages in the ORed depends will be removed.
179                 unsat = 0
180                 for dep_package, _, _ in dep:
181                     if dep_package in removals:
182                         unsat += 1
183                 if unsat == len(dep):
184                     component = p2c[package]
185                     source = sources[package]
186                     if component != "main":
187                         source = "%s/%s" % (source, component)
188                     all_broken.setdefault(source, {}).setdefault(package, set()).add(architecture)
189                     dep_problem = 1
190
191     if all_broken:
192         print "# Broken Depends:"
193         for source, bindict in sorted(all_broken.items()):
194             lines = []
195             for binary, arches in sorted(bindict.items()):
196                 if arches == all_arches:
197                     lines.append(binary)
198                 else:
199                     lines.append('%s [%s]' % (binary, ' '.join(sorted(arches))))
200             print '%s: %s' % (source, lines[0])
201             for line in lines[1:]:
202                 print ' ' * (len(source) + 2) + line
203         print
204
205     # Check source dependencies (Build-Depends and Build-Depends-Indep)
206     all_broken.clear()
207     for component in components:
208         filename = "%s/dists/%s/%s/source/Sources.gz" % (cnf["Dir::Root"], suites[0], component)
209         # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
210         (fd, temp_filename) = utils.temp_filename()
211         result, output = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
212         if result != 0:
213             sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
214             sys.exit(result)
215         sources = utils.open_file(temp_filename, "r")
216         Sources = apt_pkg.ParseTagFile(sources)
217         while Sources.Step():
218             source = Sources.Section.Find("Package")
219             if source in removals: continue
220             parsed_dep = []
221             for build_dep_type in ["Build-Depends", "Build-Depends-Indep"]:
222                 build_dep = Sources.Section.get(build_dep_type)
223                 if build_dep:
224                     # Remove [arch] information since we want to see breakage on all arches
225                     build_dep = re_build_dep_arch.sub("", build_dep)
226                     try:
227                         parsed_dep += apt_pkg.ParseDepends(build_dep)
228                     except ValueError, e:
229                         print "Error for source %s: %s" % (source, e)
230             for dep in parsed_dep:
231                 unsat = 0
232                 for dep_package, _, _ in dep:
233                     if dep_package in removals:
234                         unsat += 1
235                 if unsat == len(dep):
236                     if component != "main":
237                         source = "%s/%s" % (source, component)
238                     all_broken.setdefault(source, set()).add(utils.pp_deps(dep))
239                     dep_problem = 1
240         sources.close()
241         os.unlink(temp_filename)
242
243     if all_broken:
244         print "# Broken Build-Depends:"
245         for source, bdeps in sorted(all_broken.items()):
246             bdeps = sorted(bdeps)
247             print '%s: %s' % (source, bdeps[0])
248             for bdep in bdeps[1:]:
249                 print ' ' * (len(source) + 2) + bdep
250         print
251
252     if dep_problem:
253         print "Dependency problem found."
254         if not Options["No-Action"]:
255             game_over()
256     else:
257         print "No dependency problem found."
258     print
259
260 ################################################################################
261
262 def main ():
263     global Options
264
265     cnf = Config()
266
267     Arguments = [('h',"help","Rm::Options::Help"),
268                  ('a',"architecture","Rm::Options::Architecture", "HasArg"),
269                  ('b',"binary", "Rm::Options::Binary-Only"),
270                  ('c',"component", "Rm::Options::Component", "HasArg"),
271                  ('C',"carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
272                  ('d',"done","Rm::Options::Done", "HasArg"), # Bugs fixed
273                  ('D',"do-close","Rm::Options::Do-Close"),
274                  ('R',"rdep-check", "Rm::Options::Rdep-Check"),
275                  ('m',"reason", "Rm::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
276                  ('n',"no-action","Rm::Options::No-Action"),
277                  ('p',"partial", "Rm::Options::Partial"),
278                  ('s',"suite","Rm::Options::Suite", "HasArg"),
279                  ('S',"source-only", "Rm::Options::Source-Only"),
280                  ]
281
282     for i in [ "architecture", "binary-only", "carbon-copy", "component",
283                "done", "help", "no-action", "partial", "rdep-check", "reason",
284                "source-only" ]:
285         if not cnf.has_key("Rm::Options::%s" % (i)):
286             cnf["Rm::Options::%s" % (i)] = ""
287     if not cnf.has_key("Rm::Options::Suite"):
288         cnf["Rm::Options::Suite"] = "unstable"
289
290     arguments = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
291     Options = cnf.SubTree("Rm::Options")
292
293     if Options["Help"]:
294         usage()
295
296     session = DBConn().session()
297
298     # Sanity check options
299     if not arguments:
300         utils.fubar("need at least one package name as an argument.")
301     if Options["Architecture"] and Options["Source-Only"]:
302         utils.fubar("can't use -a/--architecture and -S/--source-only options simultaneously.")
303     if Options["Binary-Only"] and Options["Source-Only"]:
304         utils.fubar("can't use -b/--binary-only and -S/--source-only options simultaneously.")
305     if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
306         utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.")
307     if Options["Architecture"] and not Options["Partial"]:
308         utils.warn("-a/--architecture implies -p/--partial.")
309         Options["Partial"] = "true"
310     if Options["Do-Close"] and not Options["Done"]:
311         utils.fubar("No.")
312     if Options["Do-Close"] and Options["Binary-Only"]:
313         utils.fubar("No.")
314     if Options["Do-Close"] and Options["Source-Only"]:
315         utils.fubar("No.")
316     if Options["Do-Close"] and Options["Suite"] != 'unstable':
317         utils.fubar("No.")
318
319     # Force the admin to tell someone if we're not doing a 'dak
320     # cruft-report' inspired removal (or closing a bug, which counts
321     # as telling someone).
322     if not Options["No-Action"] and not Options["Carbon-Copy"] \
323            and not Options["Done"] and Options["Reason"].find("[auto-cruft]") == -1:
324         utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal.")
325
326     # Process -C/--carbon-copy
327     #
328     # Accept 3 types of arguments (space separated):
329     #  1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
330     #  2) the keyword 'package' - cc's $package@packages.debian.org for every argument
331     #  3) contains a '@' - assumed to be an email address, used unmofidied
332     #
333     carbon_copy = []
334     for copy_to in utils.split_args(Options.get("Carbon-Copy")):
335         if copy_to.isdigit():
336             carbon_copy.append(copy_to + "@" + cnf["Dinstall::BugServer"])
337         elif copy_to == 'package':
338             for package in arguments:
339                 carbon_copy.append(package + "@" + cnf["Dinstall::PackagesServer"])
340                 if cnf.has_key("Dinstall::TrackingServer"):
341                     carbon_copy.append(package + "@" + cnf["Dinstall::TrackingServer"])
342         elif '@' in copy_to:
343             carbon_copy.append(copy_to)
344         else:
345             utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to))
346
347     if Options["Binary-Only"]:
348         field = "b.package"
349     else:
350         field = "s.source"
351     con_packages = "AND %s IN (%s)" % (field, ", ".join([ repr(i) for i in arguments ]))
352
353     (con_suites, con_architectures, con_components, check_source) = \
354                  utils.parse_args(Options)
355
356     # Additional suite checks
357     suite_ids_list = []
358     suites = utils.split_args(Options["Suite"])
359     suites_list = utils.join_with_commas_and(suites)
360     if not Options["No-Action"]:
361         for suite in suites:
362             s = get_suite(suite, session=session)
363             if s is not None:
364                 suite_ids_list.append(s.suite_id)
365             if suite == "stable":
366                 print "**WARNING** About to remove from the stable suite!"
367                 print "This should only be done just prior to a (point) release and not at"
368                 print "any other time."
369                 game_over()
370             elif suite == "testing":
371                 print "**WARNING About to remove from the testing suite!"
372                 print "There's no need to do this normally as removals from unstable will"
373                 print "propogate to testing automagically."
374                 game_over()
375
376     # Additional architecture checks
377     if Options["Architecture"] and check_source:
378         utils.warn("'source' in -a/--argument makes no sense and is ignored.")
379
380     # Additional component processing
381     over_con_components = con_components.replace("c.id", "component")
382
383     print "Working...",
384     sys.stdout.flush()
385     to_remove = []
386     maintainers = {}
387
388     # We have 3 modes of package selection: binary-only, source-only
389     # and source+binary.  The first two are trivial and obvious; the
390     # latter is a nasty mess, but very nice from a UI perspective so
391     # we try to support it.
392
393     # XXX: TODO: This all needs converting to use placeholders or the object
394     #            API. It's an SQL injection dream at the moment
395
396     if Options["Binary-Only"]:
397         # Binary-only
398         q = session.execute("SELECT b.package, b.version, a.arch_string, b.id, b.maintainer FROM binaries b, bin_associations ba, architecture a, suite su, files f, location l, component c WHERE ba.bin = b.id AND ba.suite = su.id AND b.architecture = a.id AND b.file = f.id AND f.location = l.id AND l.component = c.id %s %s %s %s" % (con_packages, con_suites, con_components, con_architectures))
399         for i in q.fetchall():
400             to_remove.append(i)
401     else:
402         # Source-only
403         source_packages = {}
404         q = session.execute("SELECT l.path, f.filename, s.source, s.version, 'source', s.id, s.maintainer FROM source s, src_associations sa, suite su, files f, location l, component c WHERE sa.source = s.id AND sa.suite = su.id AND s.file = f.id AND f.location = l.id AND l.component = c.id %s %s %s" % (con_packages, con_suites, con_components))
405         for i in q.fetchall():
406             source_packages[i[2]] = i[:2]
407             to_remove.append(i[2:])
408         if not Options["Source-Only"]:
409             # Source + Binary
410             binary_packages = {}
411             # First get a list of binary package names we suspect are linked to the source
412             q = session.execute("SELECT DISTINCT b.package FROM binaries b, source s, src_associations sa, suite su, files f, location l, component c WHERE b.source = s.id AND sa.source = s.id AND sa.suite = su.id AND s.file = f.id AND f.location = l.id AND l.component = c.id %s %s %s" % (con_packages, con_suites, con_components))
413             for i in q.fetchall():
414                 binary_packages[i[0]] = ""
415             # Then parse each .dsc that we found earlier to see what binary packages it thinks it produces
416             for i in source_packages.keys():
417                 filename = "/".join(source_packages[i])
418                 try:
419                     dsc = utils.parse_changes(filename, dsc_file=1)
420                 except CantOpenError:
421                     utils.warn("couldn't open '%s'." % (filename))
422                     continue
423                 for package in dsc.get("binary").split(','):
424                     package = package.strip()
425                     binary_packages[package] = ""
426             # Then for each binary package: find any version in
427             # unstable, check the Source: field in the deb matches our
428             # source package and if so add it to the list of packages
429             # to be removed.
430             for package in binary_packages.keys():
431                 q = session.execute("SELECT l.path, f.filename, b.package, b.version, a.arch_string, b.id, b.maintainer FROM binaries b, bin_associations ba, architecture a, suite su, files f, location l, component c WHERE ba.bin = b.id AND ba.suite = su.id AND b.architecture = a.id AND b.file = f.id AND f.location = l.id AND l.component = c.id %s %s %s AND b.package = '%s'" % (con_suites, con_components, con_architectures, package))
432                 for i in q.fetchall():
433                     filename = "/".join(i[:2])
434                     control = apt_pkg.ParseSection(apt_inst.debExtractControl(utils.open_file(filename)))
435                     source = control.Find("Source", control.Find("Package"))
436                     source = re_strip_source_version.sub('', source)
437                     if source_packages.has_key(source):
438                         to_remove.append(i[2:])
439     print "done."
440
441     if not to_remove:
442         print "Nothing to do."
443         sys.exit(0)
444
445     # If we don't have a reason; spawn an editor so the user can add one
446     # Write the rejection email out as the <foo>.reason file
447     if not Options["Reason"] and not Options["No-Action"]:
448         (fd, temp_filename) = utils.temp_filename()
449         editor = os.environ.get("EDITOR","vi")
450         result = os.system("%s %s" % (editor, temp_filename))
451         if result != 0:
452             utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
453         temp_file = utils.open_file(temp_filename)
454         for line in temp_file.readlines():
455             Options["Reason"] += line
456         temp_file.close()
457         os.unlink(temp_filename)
458
459     # Generate the summary of what's to be removed
460     d = {}
461     for i in to_remove:
462         package = i[0]
463         version = i[1]
464         architecture = i[2]
465         maintainer = i[4]
466         maintainers[maintainer] = ""
467         if not d.has_key(package):
468             d[package] = {}
469         if not d[package].has_key(version):
470             d[package][version] = []
471         if architecture not in d[package][version]:
472             d[package][version].append(architecture)
473
474     maintainer_list = []
475     for maintainer_id in maintainers.keys():
476         maintainer_list.append(get_maintainer(maintainer_id).name)
477     summary = ""
478     removals = d.keys()
479     removals.sort()
480     for package in removals:
481         versions = d[package].keys()
482         versions.sort(apt_pkg.VersionCompare)
483         for version in versions:
484             d[package][version].sort(utils.arch_compare_sw)
485             summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]))
486     print "Will remove the following packages from %s:" % (suites_list)
487     print
488     print summary
489     print "Maintainer: %s" % ", ".join(maintainer_list)
490     if Options["Done"]:
491         print "Will also close bugs: "+Options["Done"]
492     if carbon_copy:
493         print "Will also send CCs to: " + ", ".join(carbon_copy)
494     print
495     print "------------------- Reason -------------------"
496     print Options["Reason"]
497     print "----------------------------------------------"
498     print
499
500     if Options["Rdep-Check"]:
501         arches = utils.split_args(Options["Architecture"])
502         reverse_depends_check(removals, suites, arches)
503
504     # If -n/--no-action, drop out here
505     if Options["No-Action"]:
506         sys.exit(0)
507
508     print "Going to remove the packages now."
509     game_over()
510
511     whoami = utils.whoami()
512     date = commands.getoutput('date -R')
513
514     # Log first; if it all falls apart I want a record that we at least tried.
515     logfile = utils.open_file(cnf["Rm::LogFile"], 'a')
516     logfile.write("=========================================================================\n")
517     logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami))
518     logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary))
519     if Options["Done"]:
520         logfile.write("Closed bugs: %s\n" % (Options["Done"]))
521     logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]))
522     logfile.write("----------------------------------------------\n")
523     logfile.flush()
524
525     # Do the same in rfc822 format
526     logfile822 = utils.open_file(cnf["Rm::LogFile822"], 'a')
527     logfile822.write("Date: %s\n" % date)
528     logfile822.write("Ftpmaster: %s\n" % whoami)
529     logfile822.write("Suite: %s\n" % suites_list)
530     sources = []
531     binaries = []
532     for package in summary.split("\n"):
533         for row in package.split("\n"):
534             element = row.split("|")
535             if len(element) == 3:
536                 if element[2].find("source") > 0:
537                     sources.append("%s_%s" % tuple(elem.strip(" ") for elem in element[:2]))
538                     element[2] = sub("source\s?,?", "", element[2]).strip(" ")
539                 if element[2]:
540                     binaries.append("%s_%s [%s]" % tuple(elem.strip(" ") for elem in element))
541     if sources:
542         logfile822.write("Sources:\n")
543         for source in sources:
544             logfile822.write(" %s\n" % source)
545     if binaries:
546         logfile822.write("Binaries:\n")
547         for binary in binaries:
548             logfile822.write(" %s\n" % binary)
549     logfile822.write("Reason: %s\n" % Options["Reason"].replace('\n', '\n '))
550     if Options["Done"]:
551         logfile822.write("Bug: %s\n" % Options["Done"])
552     logfile822.write("\n")
553     logfile822.flush()
554     logfile822.close()
555
556     dsc_type_id = get_override_type('dsc', session).overridetype_id
557     deb_type_id = get_override_type('deb', session).overridetype_id
558
559     # Do the actual deletion
560     print "Deleting...",
561     sys.stdout.flush()
562
563     for i in to_remove:
564         package = i[0]
565         architecture = i[2]
566         package_id = i[3]
567         for suite_id in suite_ids_list:
568             if architecture == "source":
569                 session.execute("DELETE FROM src_associations WHERE source = :packageid AND suite = :suiteid",
570                                 {'packageid': package_id, 'suiteid': suite_id})
571                 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id)
572             else:
573                 session.execute("DELETE FROM bin_associations WHERE bin = :packageid AND suite = :suiteid",
574                                 {'packageid': package_id, 'suiteid': suite_id})
575                 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id)
576             # Delete from the override file
577             if not Options["Partial"]:
578                 if architecture == "source":
579                     type_id = dsc_type_id
580                 else:
581                     type_id = deb_type_id
582                 # TODO: Again, fix this properly to remove the remaining non-bind argument
583                 session.execute("DELETE FROM override WHERE package = :package AND type = :typeid AND suite = :suiteid %s" % (over_con_components), {'package': package, 'typeid': type_id, 'suiteid': suite_id})
584     session.commit()
585     print "done."
586
587     # Send the bug closing messages
588     if Options["Done"]:
589         Subst = {}
590         Subst["__RM_ADDRESS__"] = cnf["Rm::MyEmailAddress"]
591         Subst["__BUG_SERVER__"] = cnf["Dinstall::BugServer"]
592         bcc = []
593         if cnf.Find("Dinstall::Bcc") != "":
594             bcc.append(cnf["Dinstall::Bcc"])
595         if cnf.Find("Rm::Bcc") != "":
596             bcc.append(cnf["Rm::Bcc"])
597         if bcc:
598             Subst["__BCC__"] = "Bcc: " + ", ".join(bcc)
599         else:
600             Subst["__BCC__"] = "X-Filler: 42"
601         Subst["__CC__"] = "X-DAK: dak rm"
602         if carbon_copy:
603             Subst["__CC__"] += "\nCc: " + ", ".join(carbon_copy)
604         Subst["__SUITE_LIST__"] = suites_list
605         summarymail = "%s\n------------------- Reason -------------------\n%s\n" % (summary, Options["Reason"])
606         summarymail += "----------------------------------------------\n"
607         Subst["__SUMMARY__"] = summarymail
608         Subst["__SUBJECT__"] = "Removed package(s) from %s" % (suites_list)
609         Subst["__ADMIN_ADDRESS__"] = cnf["Dinstall::MyAdminAddress"]
610         Subst["__DISTRO__"] = cnf["Dinstall::MyDistribution"]
611         Subst["__WHOAMI__"] = whoami
612         whereami = utils.where_am_i()
613         Archive = cnf.SubTree("Archive::%s" % (whereami))
614         Subst["__MASTER_ARCHIVE__"] = Archive["OriginServer"]
615         Subst["__PRIMARY_MIRROR__"] = Archive["PrimaryMirror"]
616         for bug in utils.split_args(Options["Done"]):
617             Subst["__BUG_NUMBER__"] = bug
618             mail_message = utils.TemplateSubst(Subst,cnf["Dir::Templates"]+"/rm.bug-close")
619             utils.send_mail(mail_message)
620
621     # close associated bug reports 
622     if Options["Do-Close"]:
623         Subst = {}
624         Subst["__RM_ADDRESS__"] = cnf["Rm::MyEmailAddress"]
625         Subst["__BUG_SERVER__"] = cnf["Dinstall::BugServer"]
626         bcc = []
627         if cnf.Find("Dinstall::Bcc") != "":
628             bcc.append(cnf["Dinstall::Bcc"])
629         if cnf.Find("Rm::Bcc") != "":
630             bcc.append(cnf["Rm::Bcc"])
631         if bcc:
632             Subst["__BCC__"] = "Bcc: " + ", ".join(bcc)
633         else:
634             Subst["__BCC__"] = "X-Filler: 42"
635         Subst["__CC__"] = "X-DAK: dak rm"
636         if carbon_copy:
637             Subst["__CC__"] += "\nCc: " + ", ".join(carbon_copy)
638         Subst["__SUITE_LIST__"] = suites_list
639         Subst["__SUBJECT__"] = "Removed package(s) from %s" % (suites_list)
640         Subst["__ADMIN_ADDRESS__"] = cnf["Dinstall::MyAdminAddress"]
641         Subst["__DISTRO__"] = cnf["Dinstall::MyDistribution"]
642         Subst["__WHOAMI__"] = whoami
643         whereami = utils.where_am_i()
644         Archive = cnf.SubTree("Archive::%s" % (whereami))
645         # at this point, I just assume, that the first closed bug gives
646         # some usefull information on why the package got removed
647         Subst["__BUG_NUMBER__"] = utils.split_args(Options["Done"])[0]
648         for bug in bts.get_bugs('src', package, 'status', 'open'):
649             Subst["__BUG_NUMBER_ALSO__"] += bug + "-done@" + cnf["Dinstall::BugServer"] + "'"
650             mail_message = utils.TemplateSubst(Subst,cnf["Dir::Templates"]+"/rm.bug-close-related")
651             utils.send_mail(mail_message)
652         
653     logfile.write("=========================================================================\n")
654     logfile.close()
655
656 #######################################################################################
657
658 if __name__ == '__main__':
659     main()