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