]> git.decadent.org.uk Git - dak.git/blob - kelly
lots and lots of python 2.1 changes. rene: remove bogus argument handling. katie...
[dak.git] / kelly
1 #!/usr/bin/env python
2
3 # Installs Debian packages
4 # Copyright (C) 2000, 2001, 2002  James Troup <james@nocrew.org>
5 # $Id: kelly,v 1.1 2002-10-16 02:47:32 troup Exp $
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 # Originally based on dinstall by Guy Maor <maor@debian.org>
22
23 ###############################################################################
24
25 #    Cartman: "I'm trying to make the best of a bad situation, I don't
26 #              need to hear crap from a bunch of hippy freaks living in
27 #              denial.  Screw you guys, I'm going home."
28 #
29 #    Kyle: "But Cartman, we're trying to..."
30 #
31 #    Cartman: "uhh.. screw you guys... home."
32
33 ###############################################################################
34
35 import FCNTL, fcntl, os, sys, time;
36 import apt_pkg;
37 import db_access, katie, logging, utils;
38
39 ###############################################################################
40
41 # Globals
42 kelly_version = "$Revision: 1.1 $";
43
44 Cnf = None;
45 Options = None;
46 Logger = None;
47 Urgency_Logger = None;
48 projectB = None;
49 Katie = None;
50 pkg = None;
51
52 reject_message = "";
53 changes = None;
54 dsc = None;
55 dsc_files = None;
56 files = None;
57 Subst = None;
58
59 install_count = 0;
60 install_bytes = 0.0;
61
62 installing_to_stable = 0;
63
64 ###############################################################################
65
66 # FIXME: this should go away to some Debian specific file
67 # FIXME: should die if file already exists
68
69 class Urgency_Log:
70     "Urgency Logger object"
71     def __init__ (self, Cnf):
72         "Initialize a new Urgency Logger object"
73         self.Cnf = Cnf;
74         self.timestamp = time.strftime("%Y%m%d%H%M%S");
75         # Create the log directory if it doesn't exist
76         self.log_dir = Cnf["Dir::UrgencyLog"];
77         if not os.path.exists(self.log_dir):
78             umask = os.umask(00000);
79             os.makedirs(self.log_dir, 02775);
80         # Open the logfile
81         self.log_filename = "%s/.install-urgencies-%s.new" % (self.log_dir, self.timestamp);
82         self.log_file = utils.open_file(self.log_filename, 'w');
83         self.writes = 0;
84
85     def log (self, source, version, urgency):
86         "Log an event"
87         self.log_file.write(" ".join([source, version, urgency])+'\n');
88         self.log_file.flush();
89         self.writes += 1;
90
91     def close (self):
92         "Close a Logger object"
93         self.log_file.flush();
94         self.log_file.close();
95         if self.writes:
96             new_filename = "%s/install-urgencies-%s" % (self.log_dir, self.timestamp);
97             utils.move(self.log_filename, new_filename);
98         else:
99             os.unlink(self.log_filename);
100
101 ###############################################################################
102
103 def reject (str, prefix="Rejected: "):
104     global reject_message;
105     if str:
106         reject_message += prefix + str + "\n";
107
108 # Recheck anything that relies on the database; since that's not
109 # frozen between accept and our run time.
110
111 def check():
112     for file in files.keys():
113         # Check that the source still exists
114         if files[file]["type"] == "deb":
115             source_version = files[file]["source version"];
116             source_package = files[file]["source package"];
117             if not changes["architecture"].has_key("source") \
118                and not Katie.source_exists(source_package, source_version):
119                 reject("no source found for %s %s (%s)." % (source_package, source_version, file));
120
121         # Version and file overwrite checks
122         if not installing_to_stable:
123             if files[file]["type"] == "deb":
124                 reject(Katie.check_binary_against_db(file));
125             elif files[file]["type"] == "dsc":
126                 reject(Katie.check_source_against_db(file));
127                 (reject_msg, is_in_incoming) = Katie.check_dsc_against_db(file);
128                 reject(reject_msg);
129
130         # Check the package is still in the override tables
131         for suite in changes["distribution"].keys():
132             if not Katie.in_override_p(files[file]["package"], files[file]["component"], suite, files[file].get("dbtype",""), file):
133                 reject("%s is NEW for %s." % (file, suite));
134
135 ###############################################################################
136
137 def init():
138     global Cnf, Options, Katie, projectB, changes, dsc, dsc_files, files, pkg, Subst;
139
140     Cnf = utils.get_conf()
141
142     Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
143                  ('h',"help","Dinstall::Options::Help"),
144                  ('m',"manual-reject","Dinstall::Options::Manual-Reject", "HasArg"),
145                  ('n',"no-action","Dinstall::Options::No-Action"),
146                  ('p',"no-lock", "Dinstall::Options::No-Lock"),
147                  ('s',"no-mail", "Dinstall::Options::No-Mail"),
148                  ('V',"version","Dinstall::Options::Version")];
149
150     for i in ["automatic", "help", "manual-reject", "no-action",
151               "no-lock", "no-mail", "version"]:
152         if not Cnf.has_key("Dinstall::Options::%s" % (i)):
153             Cnf["Dinstall::Options::%s" % (i)] = "";
154
155     changes_files = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
156     Options = Cnf.SubTree("Dinstall::Options")
157
158     Katie = katie.Katie(Cnf);
159     projectB = Katie.projectB;
160
161     changes = Katie.pkg.changes;
162     dsc = Katie.pkg.dsc;
163     dsc_files = Katie.pkg.dsc_files;
164     files = Katie.pkg.files;
165     pkg = Katie.pkg;
166     Subst = Katie.Subst;
167
168     return changes_files;
169
170 ###############################################################################
171
172 def usage (exit_code=0):
173     print """Usage: dinstall [OPTION]... [CHANGES]...
174   -a, --automatic           automatic run
175   -h, --help                show this help and exit.
176   -n, --no-action           don't do anything
177   -p, --no-lock             don't check lockfile !! for cron.daily only !!
178   -s, --no-mail             don't send any mail
179   -V, --version             display the version number and exit"""
180     sys.exit(exit_code)
181
182 ###############################################################################
183
184 def action ():
185     (summary, short_summary) = Katie.build_summaries();
186
187     (prompt, answer) = ("", "XXX")
188     if Options["No-Action"] or Options["Automatic"]:
189         answer = 'S'
190
191     if reject_message.find("Rejected") != -1:
192         print "REJECT\n" + reject_message,;
193         prompt = "[R]eject, Skip, Quit ?";
194         if Options["Automatic"]:
195             answer = 'R';
196     else:
197         print "INSTALL\n" + reject_message + summary,;
198         prompt = "[I]nstall, Skip, Quit ?";
199         if Options["Automatic"]:
200             answer = 'I';
201
202     while prompt.find(answer) == -1:
203         answer = utils.our_raw_input(prompt);
204         m = katie.re_default_answer.match(prompt);
205         if answer == "":
206             answer = m.group(1);
207         answer = answer[:1].upper();
208
209     if answer == 'R':
210         do_reject ();
211     elif answer == 'I':
212         if not installing_to_stable:
213             install();
214         else:
215             stable_install(summary, short_summary);
216     elif answer == 'Q':
217         sys.exit(0)
218
219 ###############################################################################
220
221 # Our reject is not really a reject, but an unaccept, but since a) the
222 # code for that is non-trivial (reopen bugs, unannounce etc.), b) this
223 # should be exteremly rare, for now we'll go with whining at our admin
224 # folks...
225
226 def do_reject ():
227     Subst["__REJECTOR_ADDRESS__"] = Cnf["Dinstall::MyEmailAddress"];
228     Subst["__REJECT_MESSAGE__"] = reject_message;
229     Subst["__CC__"] = "Cc: " + Cnf["Dinstall::MyEmailAddress"];
230     reject_mail_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/kelly.unaccept");
231
232     # Write the rejection email out as the <foo>.reason file
233     reason_filename = os.path.basename(pkg.changes_file[:-8]) + ".reason";
234     reject_filename = Cnf["Dir::Queue::Reject"] + '/' + reason_filename;
235     # If we fail here someone is probably trying to exploit the race
236     # so let's just raise an exception ...
237     if os.path.exists(reject_filename):
238         os.unlink(reject_filename);
239     fd = os.open(reject_filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0644);
240     os.write(fd, reject_mail_message);
241     os.close(fd);
242
243     utils.send_mail (reject_mail_message, "");
244     Logger.log(["unaccepted", pkg.changes_file]);
245
246 ###############################################################################
247
248 def install ():
249     global install_count, install_bytes;
250
251     print "Installing."
252
253     Logger.log(["installing changes",pkg.changes_file]);
254
255     # Begin a transaction; if we bomb out anywhere between here and the COMMIT WORK below, the DB will not be changed.
256     projectB.query("BEGIN WORK");
257
258     # Add the .dsc file to the DB
259     for file in files.keys():
260         if files[file]["type"] == "dsc":
261             package = dsc["source"]
262             version = dsc["version"]  # NB: not files[file]["version"], that has no epoch
263             maintainer = dsc["maintainer"]
264             maintainer = maintainer.replace("'", "\\'")
265             maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
266             fingerprint_id = db_access.get_or_set_fingerprint_id(dsc["fingerprint"]);
267             install_date = time.strftime("%Y-%m-%d");
268             filename = files[file]["pool name"] + file;
269             dsc_location_id = files[file]["location id"];
270             if not files[file].has_key("files id") or not files[file]["files id"]:
271                 files[file]["files id"] = db_access.set_files_id (filename, files[file]["size"], files[file]["md5sum"], dsc_location_id)
272             projectB.query("INSERT INTO source (source, version, maintainer, file, install_date, sig_fpr) VALUES ('%s', '%s', %d, %d, '%s', %s)"
273                            % (package, version, maintainer_id, files[file]["files id"], install_date, fingerprint_id));
274
275             for suite in changes["distribution"].keys():
276                 suite_id = db_access.get_suite_id(suite);
277                 projectB.query("INSERT INTO src_associations (suite, source) VALUES (%d, currval('source_id_seq'))" % (suite_id))
278
279             # Add the source files to the DB (files and dsc_files)
280             projectB.query("INSERT INTO dsc_files (source, file) VALUES (currval('source_id_seq'), %d)" % (files[file]["files id"]));
281             for dsc_file in dsc_files.keys():
282                 filename = files[file]["pool name"] + dsc_file;
283                 # If the .orig.tar.gz is already in the pool, it's
284                 # files id is stored in dsc_files by check_dsc().
285                 files_id = dsc_files[dsc_file].get("files id", None);
286                 if files_id == None:
287                     files_id = db_access.get_files_id(filename, dsc_files[dsc_file]["size"], dsc_files[dsc_file]["md5sum"], dsc_location_id);
288                 # FIXME: needs to check for -1/-2 and or handle exception
289                 if files_id == None:
290                     files_id = db_access.set_files_id (filename, dsc_files[dsc_file]["size"], dsc_files[dsc_file]["md5sum"], dsc_location_id);
291                 projectB.query("INSERT INTO dsc_files (source, file) VALUES (currval('source_id_seq'), %d)" % (files_id));
292
293     # Add the .deb files to the DB
294     for file in files.keys():
295         if files[file]["type"] == "deb":
296             package = files[file]["package"]
297             version = files[file]["version"]
298             maintainer = files[file]["maintainer"]
299             maintainer = maintainer.replace("'", "\\'")
300             maintainer_id = db_access.get_or_set_maintainer_id(maintainer);
301             fingerprint_id = db_access.get_or_set_fingerprint_id(changes["fingerprint"]);
302             architecture = files[file]["architecture"]
303             architecture_id = db_access.get_architecture_id (architecture);
304             type = files[file]["dbtype"];
305             dsc_component = files[file]["component"]
306             source = files[file]["source package"]
307             source_version = files[file]["source version"];
308             filename = files[file]["pool name"] + file;
309             if not files[file].has_key("location id") or not files[file]["location id"]:
310                 files[file]["location id"] = db_access.get_location_id(Cnf["Dir::Pool"],files[file]["component"],utils.where_am_i());
311             if not files[file].has_key("files id") or not files[file]["files id"]:
312                 files[file]["files id"] = db_access.set_files_id (filename, files[file]["size"], files[file]["md5sum"], files[file]["location id"])
313             source_id = db_access.get_source_id (source, source_version);
314             if source_id:
315                 projectB.query("INSERT INTO binaries (package, version, maintainer, source, architecture, file, type, sig_fpr) VALUES ('%s', '%s', %d, %d, %d, %d, '%s', %d)"
316                                % (package, version, maintainer_id, source_id, architecture_id, files[file]["files id"], type, fingerprint_id));
317             else:
318                 projectB.query("INSERT INTO binaries (package, version, maintainer, architecture, file, type, sig_fpr) VALUES ('%s', '%s', %d, %d, %d, '%s', %d)"
319                                % (package, version, maintainer_id, architecture_id, files[file]["files id"], type, fingerprint_id));
320             for suite in changes["distribution"].keys():
321                 suite_id = db_access.get_suite_id(suite);
322                 projectB.query("INSERT INTO bin_associations (suite, bin) VALUES (%d, currval('binaries_id_seq'))" % (suite_id));
323
324     # If the .orig.tar.gz is in a legacy directory we need to poolify
325     # it, so that apt-get source (and anything else that goes by the
326     # "Directory:" field in the Sources.gz file) works.
327     orig_tar_id = Katie.pkg.orig_tar_id;
328     orig_tar_location = Katie.pkg.orig_tar_location;
329     legacy_source_untouchable = Katie.pkg.legacy_source_untouchable;
330     if orig_tar_id != None and orig_tar_location == "legacy":
331         q = projectB.query("SELECT DISTINCT ON (f.id) l.path, f.filename, f.id as files_id, df.source, df.id as dsc_files_id, f.size, f.md5sum FROM files f, dsc_files df, location l WHERE df.source IN (SELECT source FROM dsc_files WHERE file = %s) AND f.id = df.file AND l.id = f.location AND (l.type = 'legacy' OR l.type = 'legacy-mixed')" % (orig_tar_id));
332         qd = q.dictresult();
333         for qid in qd:
334             # Is this an old upload superseded by a newer -sa upload?  (See check_dsc() for details)
335             if legacy_source_untouchable.has_key(qid["files_id"]):
336                 continue;
337             # First move the files to the new location
338             legacy_filename = qid["path"] + qid["filename"];
339             pool_location = utils.poolify (changes["source"], files[file]["component"]);
340             pool_filename = pool_location + os.path.basename(qid["filename"]);
341             destination = Cnf["Dir::Pool"] + pool_location
342             utils.move(legacy_filename, destination);
343             # Then Update the DB's files table
344             q = projectB.query("UPDATE files SET filename = '%s', location = '%s' WHERE id = '%s'" % (pool_filename, dsc_location_id, qid["files_id"]));
345
346     # If this is a sourceful diff only upload that is moving non-legacy
347     # cross-component we need to copy the .orig.tar.gz into the new
348     # component too for the same reasons as above.
349     #
350     if changes["architecture"].has_key("source") and orig_tar_id != None and \
351        orig_tar_location != "legacy" and orig_tar_location != dsc_location_id:
352         q = projectB.query("SELECT l.path, f.filename, f.size, f.md5sum FROM files f, location l WHERE f.id = %s AND f.location = l.id" % (orig_tar_id));
353         ql = q.getresult()[0];
354         old_filename = ql[0] + ql[1];
355         file_size = ql[2];
356         file_md5sum = ql[3];
357         new_filename = utils.poolify(changes["source"], dsc_component) + os.path.basename(old_filename);
358         new_files_id = db_access.get_files_id(new_filename, file_size, file_md5sum, dsc_location_id);
359         if new_files_id == None:
360             utils.copy(old_filename, Cnf["Dir::Pool"] + new_filename);
361             new_files_id = db_access.set_files_id(new_filename, file_size, file_md5sum, dsc_location_id);
362             projectB.query("UPDATE dsc_files SET file = %s WHERE source = %s AND file = %s" % (new_files_id, source_id, orig_tar_id));
363
364     # Install the files into the pool
365     for file in files.keys():
366         destination = Cnf["Dir::Pool"] + files[file]["pool name"] + file;
367         utils.move(file, destination);
368         Logger.log(["installed", file, files[file]["type"], files[file]["size"], files[file]["architecture"]]);
369         install_bytes += float(files[file]["size"]);
370
371     # Copy the .changes file across for suite which need it.
372     copy_changes_p = copy_katie_p = 0;
373     for suite in changes["distribution"].keys():
374         if Cnf.has_key("Suite::%s::CopyChanges" % (suite)):
375             copy_changes_p = 1;
376         # and the .katie file...
377         if Cnf.has_key("Suite::%s::CopyKatie" % (suite)):
378             copy_katie_p = 1;
379     if copy_changes_p:
380         utils.copy(pkg.changes_file, Cnf["Dir::Root"] + Cnf["Suite::%s::CopyChanges" % (suite)]);
381     if copy_katie_p:
382         utils.copy(Katie.pkg.changes_file[:-8]+".katie", Cnf["Suite::%s::CopyKatie" % (suite)]);
383
384     projectB.query("COMMIT WORK");
385
386     # Move the .changes into the 'done' directory
387     try:
388         utils.move (pkg.changes_file, os.path.join(Cnf["Dir::Queue::Done"], os.path.basename(pkg.changes_file)));
389     except:
390         utils.warn("couldn't move changes file '%s' to DONE directory. [Got %s]" % (os.path.basename(pkg.changes_file), sys.exc_type));
391
392     os.unlink(Katie.pkg.changes_file[:-8]+".katie");
393
394     if changes["architecture"].has_key("source") and Urgency_Logger:
395         Urgency_Logger.log(dsc["source"], dsc["version"], changes["urgency"]);
396
397     # Undo the work done in katie.py(accept) to help auto-building
398     # from accepted.
399     projectB.query("BEGIN WORK");
400     for suite in changes["distribution"].keys():
401         if suite not in Cnf.ValueList("Dinstall::AcceptedAutoBuildSuites"):
402             continue;
403         now_date = time.strftime("%Y-%m-%d %H:%M");
404         suite_id = db_access.get_suite_id(suite);
405         dest_dir = Cnf["Dir::AcceptedAutoBuild"];
406         if Cnf.FindB("Dinstall::SecurityAcceptedAutoBuild"):
407             dest_dir = os.path.join(dest_dir, suite);
408         for file in files.keys():
409             dest = os.path.join(dest_dir, file);
410             # Remove it from the list of packages for later processing by apt-ftparchive
411             projectB.query("UPDATE accepted_autobuild SET in_accepted = 'f', last_used = '%s' WHERE filename = '%s' AND suite = %s" % (now_date, dest, suite_id));
412             if not Cnf.FindB("Dinstall::SecurityAcceptedAutoBuild"):
413                 # Update the symlink to point to the new location in the pool
414                 pool_location = utils.poolify (changes["source"], files[file]["component"]);
415                 src = os.path.join(Cnf["Dir::Pool"], pool_location, os.path.basename(file));
416                 if os.path.islink(dest):
417                     os.unlink(dest);
418                 os.symlink(src, dest);
419         # Update last_used on any non-upload .orig.tar.gz symlink
420         if orig_tar_id:
421             # Determine the .orig.tar.gz file name
422             for dsc_file in dsc_files.keys():
423                 if dsc_file.endswith(".orig.tar.gz"):
424                     orig_tar_gz = os.path.join(dest_dir, dsc_file);
425             # Remove it from the list of packages for later processing by apt-ftparchive
426             projectB.query("UPDATE accepted_autobuild SET in_accepted = 'f', last_used = '%s' WHERE filename = '%s' AND suite = %s" % (now_date, orig_tar_gz, suite_id));
427     projectB.query("COMMIT WORK");
428
429     # Finally...
430     install_count += 1;
431
432 ################################################################################
433
434 def stable_install (summary, short_summary):
435     global install_count;
436
437     print "Installing to stable.";
438
439     # Begin a transaction; if we bomb out anywhere between here and the COMMIT WORK below, the DB will not be changed.
440     projectB.query("BEGIN WORK");
441
442     # Add the source to stable (and remove it from proposed-updates)
443     for file in files.keys():
444         if files[file]["type"] == "dsc":
445             package = dsc["source"];
446             version = dsc["version"];  # NB: not files[file]["version"], that has no epoch
447             q = projectB.query("SELECT id FROM source WHERE source = '%s' AND version = '%s'" % (package, version))
448             ql = q.getresult();
449             if not ql:
450                 utils.fubar("[INTERNAL ERROR] couldn't find '%s' (%s) in source table." % (package, version));
451             source_id = ql[0][0];
452             suite_id = db_access.get_suite_id('proposed-updates');
453             projectB.query("DELETE FROM src_associations WHERE suite = '%s' AND source = '%s'" % (suite_id, source_id));
454             suite_id = db_access.get_suite_id('stable');
455             projectB.query("INSERT INTO src_associations (suite, source) VALUES ('%s', '%s')" % (suite_id, source_id));
456
457     # Add the binaries to stable (and remove it/them from proposed-updates)
458     for file in files.keys():
459         if files[file]["type"] == "deb":
460             package = files[file]["package"];
461             version = files[file]["version"];
462             architecture = files[file]["architecture"];
463             q = projectB.query("SELECT b.id FROM binaries b, architecture a WHERE b.package = '%s' AND b.version = '%s' AND (a.arch_string = '%s' OR a.arch_string = 'all') AND b.architecture = a.id" % (package, version, architecture));
464             ql = q.getresult();
465             if not ql:
466                 utils.fubar("[INTERNAL ERROR] couldn't find '%s' (%s for %s architecture) in binaries table." % (package, version, architecture));
467             binary_id = ql[0][0];
468             suite_id = db_access.get_suite_id('proposed-updates');
469             projectB.query("DELETE FROM bin_associations WHERE suite = '%s' AND bin = '%s'" % (suite_id, binary_id));
470             suite_id = db_access.get_suite_id('stable');
471             projectB.query("INSERT INTO bin_associations (suite, bin) VALUES ('%s', '%s')" % (suite_id, binary_id));
472
473     projectB.query("COMMIT WORK");
474
475     utils.move (pkg.changes_file, Cnf["Dir::Morgue"] + '/katie/' + os.path.basename(pkg.changes_file));
476
477     ## Update the Stable ChangeLog file
478     new_changelog_filename = Cnf["Dir::Root"] + Cnf["Suite::Stable::ChangeLogBase"] + ".ChangeLog";
479     changelog_filename = Cnf["Dir::Root"] + Cnf["Suite::Stable::ChangeLogBase"] + "ChangeLog";
480     if os.path.exists(new_changelog_filename):
481         os.unlink (new_changelog_filename);
482
483     new_changelog = utils.open_file(new_changelog_filename, 'w');
484     for file in files.keys():
485         if files[file]["type"] == "deb":
486             new_changelog.write("stable/%s/binary-%s/%s\n" % (files[file]["component"], files[file]["architecture"], file));
487         elif utils.re_issource.match(file) != None:
488             new_changelog.write("stable/%s/source/%s\n" % (files[file]["component"], file));
489         else:
490             new_changelog.write("%s\n" % (file));
491     chop_changes = katie.re_fdnic.sub("\n", changes["changes"]);
492     new_changelog.write(chop_changes + '\n\n');
493     if os.access(changelog_filename, os.R_OK) != 0:
494         changelog = utils.open_file(changelog_filename);
495         new_changelog.write(changelog.read());
496     new_changelog.close();
497     if os.access(changelog_filename, os.R_OK) != 0:
498         os.unlink(changelog_filename);
499     utils.move(new_changelog_filename, changelog_filename);
500
501     install_count += 1;
502
503     if not Options["No-Mail"] and changes["architecture"].has_key("source"):
504         Subst["__SUITE__"] = " into stable";
505         Subst["__SUMMARY__"] = summary;
506         mail_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/kelly.installed");
507         utils.send_mail(mail_message, "");
508         Katie.announce(short_summary, 1)
509
510     # Finally remove the .katie file
511     katie_file = os.path.join(Cnf["Suite::Proposed-Updates::CopyKatie"], os.path.basename(Katie.pkg.changes_file[:-8]+".katie"));
512     os.unlink(katie_file);
513
514 ################################################################################
515
516 def process_it (changes_file):
517     global reject_message;
518
519     reject_message = "";
520
521     # Absolutize the filename to avoid the requirement of being in the
522     # same directory as the .changes file.
523     pkg.changes_file = os.path.abspath(changes_file);
524
525     # And since handling of installs to stable munges with the CWD;
526     # save and restore it.
527     pkg.directory = os.getcwd();
528
529     if installing_to_stable:
530         old = Katie.pkg.changes_file;
531         Katie.pkg.changes_file = os.path.basename(old);
532         os.chdir(Cnf["Suite::Proposed-Updates::CopyKatie"]);
533
534     Katie.init_vars();
535     Katie.update_vars();
536     Katie.update_subst();
537
538     if installing_to_stable:
539         Katie.pkg.changes_file = old;
540
541     check();
542     action();
543
544     # Restore CWD
545     os.chdir(pkg.directory);
546
547 ###############################################################################
548
549 def main():
550     global projectB, Logger, Urgency_Logger, installing_to_stable;
551
552     changes_files = init();
553
554     if Options["Help"]:
555         usage();
556
557     if Options["Version"]:
558         print "kelly %s" % (kelly_version);
559         sys.exit(0);
560
561     # -n/--dry-run invalidates some other options which would involve things happening
562     if Options["No-Action"]:
563         Options["Automatic"] = "";
564
565     # Check that we aren't going to clash with the daily cron job
566
567     if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::Root"])) and not Options["No-Lock"]:
568         utils.fubar("Archive maintenance in progress.  Try again later.");
569
570     # If running from within proposed-updates; assume an install to stable
571     if os.getcwd().find('proposed-updates') != -1:
572         installing_to_stable = 1;
573
574     # Obtain lock if not in no-action mode and initialize the log
575     if not Options["No-Action"]:
576         lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
577         fcntl.lockf(lock_fd, FCNTL.F_TLOCK);
578         Logger = Katie.Logger = logging.Logger(Cnf, "katie");
579         if not installing_to_stable and Cnf.get("Dir::UrgencyLog"):
580             Urgency_Logger = Urgency_Log(Cnf);
581
582     # Initialize the substitution template mapping global
583     bcc = "X-Katie: %s" % (kelly_version);
584     if Cnf.has_key("Dinstall::Bcc"):
585         Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
586     else:
587         Subst["__BCC__"] = bcc;
588     if Cnf.has_key("Dinstall::StableRejector"):
589         Subst["__STABLE_REJECTOR__"] = Cnf["Dinstall::StableRejector"];
590
591     # Sort the .changes files so that we process sourceful ones first
592     changes_files.sort(utils.changes_compare);
593
594     # Process the changes files
595     for changes_file in changes_files:
596         print "\n" + changes_file;
597         process_it (changes_file);
598
599     if install_count:
600         sets = "set"
601         if install_count > 1:
602             sets = "sets"
603         sys.stderr.write("Installed %d package %s, %s.\n" % (install_count, sets, utils.size_type(int(install_bytes))));
604         Logger.log(["total",install_count,install_bytes]);
605
606     if not Options["No-Action"]:
607         Logger.close();
608         if Urgency_Logger:
609             Urgency_Logger.close();
610
611 ###############################################################################
612
613 if __name__ == '__main__':
614     main();