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