added dereferencing of links during snarf
[feisty_meow.git] / scripts / archival / shared_snarfer.pl
1 #!/usr/bin/perl
2
3 ###############################################################################
4 #                                                                             #
5 #  Name   : shared_snarfer                                                    #
6 #  Author : Chris Koeritz                                                     #
7 #  Rights : Copyright (C) 1996-$now by Author                                 #
8 #                                                                             #
9 #  Purpose:                                                                   #
10 #                                                                             #
11 #    A shared library collection for "snarfing up" archives.  This uses the   #
12 #  compressed tar format for files ending in ".snarf" to store collections    #
13 #  of files, folders, hierarchies and so forth.                               #
14 #                                                                             #
15 ###############################################################################
16 #  This program is free software; you can redistribute it and/or modify it    #
17 #  under the terms of the GNU General Public License as published by the Free #
18 #  Software Foundation; either version 2 of the License or (at your option)   #
19 #  any later version.  See: "http://www.gruntose.com/Info/GNU/GPL.html" for a #
20 #  version of the License.  Please send any updates to "fred@gruntose.com".   #
21 ###############################################################################
22
23 require "filename_helper.pl";
24 require "inc_num.pl";
25
26 use Cwd;
27 use Sys::Hostname;
28 use File::Which;
29 use Env qw(FEISTY_MEOW_SCRIPTS TMP);
30
31 $null_log = "/dev/null";
32
33 $TMP =~ s/\\/\//g;  # fix the temp variable for ms-winders.
34
35 # defines an array of problematic entries we were told to deal with.
36 @missing_log = ();
37
38 # these files are considered unimportant and won't be included in the archive.
39 @junk_file_list = ("*~", "*.$$$", "3rdparty", "*.aps", "*.bak", "binaries",
40     "*.bsc", "*.cgl", "*.csm", "CVS", "Debug", "*.dll", "*.err", "*.exe",
41     "generated_*", "*.git", "*.glb", "inprogress", "ipch", "*.llm",
42     "*.log", "*.lnk",
43     "makefile.fw*", "*.mbt", "*.mrt", "*.ncb", "*.o", "obj", "*.obj",
44     "octalforty.Wizardby", "*.obr", "*.opt", "packages", 
45     "*.pch", "*.pdb", "*.plg", "*.r$p", "*.rcs", "Release",
46     "*.res", "*.RES", "*.rws", "*.sbr", "*.scc", "*.spx", "*.stackdump",
47     "Steam",
48     "*.sdf", "*.suo", ".svn", "*.sym", "*.td", "*.tds", "*.tdw", "*.tlb",
49     "*.trw", "*.tmp", "*.tr", "*.user", "*_version.h", "*_version.rc",
50     "*.vspscc", "waste", "zeitgeist");
51 #print "junk list=@junk_file_list\n";
52 @excludes = ();
53 for (local($i) = 0; $i < scalar(@junk_file_list); $i++) {
54   push(@excludes, "--exclude=$junk_file_list[$i]");
55 }
56 #print "excludes list=@excludes\n";
57
58 # generic versions work on sane OSes.
59 $find_tool = which('find');
60 $tar_tool = which('tar');
61 #print "find tool: $find_tool\n";
62 #print "tar tool: $tar_tool\n";
63
64 if ( ! -f "$find_tool" || ! -f "$tar_tool" ) {
65   print "Could not locate either tar or find tools for this platform.\n";
66   exit 3;
67 }
68
69 # this is somewhat ugly, but it sets up a global variable called
70 # "original_path" so we remember where we started.
71 sub initialize_snarfer {
72   $original_path = cwd();
73   $original_path =~ s/\\/\//g;
74 }
75
76 # returns the current hostname, but without any domain included.
77 sub short_hostname {
78   local($temphost) = hostname();
79 #&hostname();
80   $temphost =~ s/([^.]*)\..*/\1/;
81   return &lower($temphost);
82 }
83
84 # takes the base name and creates the full snarf prefix name, which includes
85 # a timestamp and hostname.
86 sub snarf_prefix {
87   local($base) = @_;
88
89 #hmmm: extract this shared code to new function (also in safedel)
90   $date_tool = "date";
91   local($date_part) = `$date_tool +%Y-%m-%d-%H%M`;
92   while ($date_part =~ /[\r\n]$/) { chop $date_part; }
93
94   local($host) = &short_hostname();
95   while ($host =~ /[\r\n]$/) { chop $host; }
96   $base = $base . "_" . $host . "_" . $date_part;
97   return $base;
98 }
99
100 # returns the name of the file to create based on the prefix and the
101 # current archive number.
102 sub snarf_name {
103   local($prefix, $number) = @_;
104   local($path) = &canonicalize($original_path);
105   local($target_file) = $path . '/' . $prefix . "_" . $number . ".tar";
106   return $target_file;
107 }
108
109 # finishes up on the archive file.
110 sub finalize_snarf {
111   local($filename) = @_;
112 #print "finalizing now on filename $filename\n";
113   local($outcome) = 0xff & system "gzip", $filename;
114   if ($outcome) { die("failure to finalize"); }
115
116   if (scalar(@missing_log)) {
117     print "The following files or directories were missing:\n";
118     print "@missing_log\n";
119   }
120 }
121
122 # fixes the directory passed in, if required.  this is only needed for
123 # dos-like operating systems, where there are drives to worry about and where
124 # cygwin refuses to store the full path for an absolute pathname in the
125 # archive.  instead of letting it store partial paths, we change to the top
126 # of the drive and scoop up the files using a relative path.
127 sub chdir_to_top {
128   local($directory) = @_;
129   if ( (substr($directory, 0, 2) eq "//")
130       && (substr($directory, 3, 1) eq "/") ) {
131 #print "into special case\n";
132     # it was originally a dos path, so now we must do some directory changing
133     # magic to get the paths to work right.
134     local($drive) = substr($directory, 0, 4);  # get just drive letter biz.
135 #print "going to change to $drive\n";
136     chdir($drive);
137 #print "cwd now=" . cwd() . "\n";
138     $directory = substr($directory, 4);  # rip off absolutist path.
139 #print "using dir now as $directory\n";
140     if (length($directory) == 0) {
141 #print "caught zero length dir, patching to dot now.\n";
142       $directory = ".";
143     }
144   }
145   return $directory;
146 }
147
148 # snarfer scoops up some files in a directory.
149 sub snarfer {
150   local($prefix, $number, $root, $subdir, @extra_flags) = @_;
151 #print "prefix=$prefix, num=$number, root=$root, subdir=$subdir, extra=@extra_flags\n";
152
153   $root = &chdir_to_top($root);
154
155   local($target_file) = &snarf_name($prefix, $number);
156
157   $random_num = (rand() * 1000000) % 1000000;
158   $temp_file = `mktemp "$TMP/zz_snarf_tmp.XXXXXX"`;
159   chop($temp_file);
160
161   if (! -d $root . "/" . $subdir) {
162     local($base) = &basename($root . "/" . $subdir);
163 #print "adding to missing in snarfer A: $base\n";
164     push(@missing_log, $base);
165     return 0;
166   }
167   local($currdir) = cwd();
168   chdir($root);
169
170   local($outcome) = 0;
171   my @lines = qx( $find_tool "$subdir" @extra_flags "-type" "f" );
172 #  if ( ($! != 0) || ($? != 0) ) {
173 #    die("failure to find files in $subdir"); 
174 #  }
175
176   open TEMPY_OUT, ">>$temp_file" or die "cannot open $temp_file";
177   foreach (@lines) { print TEMPY_OUT "$_"; }
178   close TEMPY_OUT;
179
180   if (-s $temp_file == 0) {
181     local($base) = &basename($root . "/" . $subdir);
182 #print "adding to missing in snarfer B: $base\n";
183     push(@missing_log, $base);
184   }
185
186   local($outcome) = 0xff & system $tar_tool, 
187 #hmmm: trying to dereference symbolic links and stop missing stuff.
188 "-h",
189       "-rf", &canonicalize($target_file), @excludes,
190       "--files-from=" . &canonicalize($temp_file);
191   if ($outcome) {
192     unlink($temp_file);
193     die("failure to archive");
194   }
195   # clean up temporaries.
196   unlink($temp_file);
197   # change back to previous directory.
198   chdir($currdir);
199 }
200
201 # snarf_file_list is like snarfer but expects a file pattern at the end rather
202 # than a directory name.
203 sub snarf_file_list {
204   local($prefix, $number, $root, $file_pattern, @extra_flags) = @_;
205
206 #print "prefix=$prefix, num=$number, root=$root, file_pattern=$file_pattern, extra=@extra_flags\n";
207
208   $root = &chdir_to_top($root);
209
210   local($target_file) = &snarf_name($prefix, $number);
211
212   local($currdir) = cwd();
213 #print "got root as: '$root'\n";
214   chdir("$root");
215
216   local(@files) = &glob_list($file_pattern);
217   if (!scalar(@files)) {
218     local($base) = $root . "/" . $file_pattern;
219     $base =~ s/\/\//\//g;
220 #print "adding to missing in snarf_file_list: $base\n";
221     push(@missing_log, $base);
222   }
223
224   foreach $i (@files) {
225     if ($i =~ /^\.\//) {
226       $i = substr $i, 2, length($i) - 2;
227     }
228     local($outcome) = 0xff & system $tar_tool,
229 #"--directory=" . "$root",
230         @extra_flags, 
231 #hmmm: trying to dereference symbolic links and stop missing stuff.
232 "-h",
233 "-rf", &canonicalize($target_file), @excludes, $i;
234     if ($outcome) { die("failure to archive"); }
235   }
236   chdir("$currdir");
237 }
238
239 # backup some specific files.
240 sub backup_files {
241   local($prefix, $number, $root, $subdir, @files) = @_;
242 #print "backup_files: ref=$prefix, num=$number, subdir=$subdir, list of files=@files\n";
243   foreach $i (@files) {
244     local($new_path) = $subdir . "/" . $i;
245     if ($subdir eq ".") { $new_path = "$i"; }
246     &snarf_file_list($prefix, $number, $root, $new_path);
247   }
248 }
249
250 # backup some specific directories.
251 sub backup_directories {
252   local($prefix, $number, $root, $subdir, @dirs) = @_;
253 #print "backup_directories: ref=$prefix, num=$number, root=$root, subdir=$subdir, list of dirs=@dirs.\n";
254   foreach $i (@dirs) {
255     local($path_to_use) = $subdir . "/" . $i;
256     if ($i eq ".") {
257       $path_to_use = $subdir;
258     }
259     &snarfer($prefix, $number, $root, $path_to_use, ("-maxdepth", "1"));
260   }
261 }
262
263 # removes items from the file that match a pattern.
264 sub remove_from_backup {
265   local($prefix, $number, $pattern) = @_;
266 #print "remove_from_backup: pref=$prefix, num=$number, patt=$pattern,\n";
267   local($target_file) = &snarf_name($prefix, $number);
268
269   open(TARPROC, "$tar_tool --delete -f " . &canonicalize($target_file)
270       . " \"$pattern\" 2>$null_log |");
271   <TARPROC>;
272 }
273
274 # recursively scoops up a directory hierarchy.
275 sub backup_hierarchy {
276   local($prefix, $number, $root, $filepart) = @_;
277 #print "backup_hierarchy: pref=$prefix, num=$number, root=$root, filepart=$filepart\n";
278   local(@locus_temp) = &glob_list($root);
279   local($save_root) = $root;
280   local($root) = $locus_temp[0];
281   if (!length($root)) {
282     local($base) = $save_root . "/" . $filepart;
283 #print "adding to missing in backup_hierarchy A: $base\n";
284     push(@missing_log, $base);
285     return;
286   }
287   local($new_pattern) = "$root/$filepart";
288   if ($root =~ /\/$/) { $new_pattern = "$root$filepart"; }
289   local(@mod_locus) = &glob_list($new_pattern);
290   if (!scalar(@mod_locus)) {
291     local($base) = &basename($root . "/" . $filepart);
292 #print "adding to missing in backup_hierarchy B: $base\n";
293     push(@missing_log, $base);
294   } else {
295     foreach $i (@mod_locus) {
296       local($new_locus) = $root;
297       local $offset_len = length($root) + 1;
298       local $char_len = length($i) - length($root) - 1;
299       # make sure we don't double slashes up if one's already there.
300       if ($root =~ /\/$/) { $offset_len--; $char_len++; }
301       local($extra_portion) = substr $i, $offset_len, $char_len;
302       if (!length($extra_portion)) {
303         # well, in this case, there's nothing left of the extra part after
304         # the root.  we'll push the last component of the root down into
305         # the extra part so there's actually something to traverse.
306         $new_locus = &dirname($root);
307         $extra_portion = &basename($root);
308       }
309       &snarfer($prefix, $number, $new_locus, $extra_portion, ());
310     }
311   }
312 }
313
314 # recursively scoop up a list of directory hierarchies.
315 sub backup_hierarchies {
316   local($prefix, $number, $root, @dirs) = @_;
317 #  print "backup_hierarchy: pref=$prefix, num=$number, root=$root,\n";
318 #  print "list of dirs=@dirs.\n";
319   foreach $i (@dirs) {
320     &backup_hierarchy($prefix, $number, $root, $i);
321   }
322 }
323
324 # grab up all the files in a directory (second parm) that are named matching
325 # a simple text pattern (third parm).  if there is a fourth parameter, it is
326 # used as an extra directory component after the main directory.
327 sub snarf_by_pattern {
328   local($prefix, $dir, $pattern, $extra_component) = @_;
329   local($had_extra) = length($extra_component) != 0;
330 #print "snarf by pattern, dir = $dir, patt = $pattern, extra = $extra_component\n";
331   if ($had_extra) {
332     $dir = "$dir/$extra_component";
333   }
334   @dir_contents = &glob_list("$dir/*$pattern*"); 
335 #print "dir contents: @dir_contents\n";
336
337   if (!scalar(@dir_contents)) {
338     print "no '$pattern' directores were backed up in $dir.\n";
339   }
340   
341   foreach $item (@dir_contents) {
342     if ( ($item =~ /$pattern.*snarf/) || ($item =~ /$pattern.*tar/) ) { next; }
343     if ( ! -d "$item" ) { next; }
344 #print "now really planning to backup hier of $item\n";
345     # normal backup had no extra component.
346     local $upper_dir = &dirname($item);
347     local $dir_plus_base = &basename($item);
348     # if we did have an extra component, we do this a bit differently.
349     if ($had_extra) {
350       $upper_dir = &dirname( &dirname($item) );
351       $dir_plus_base = &basename( &dirname($item) ) . "/" . &basename($item);
352     }
353 #print "using upper=$upper_dir and dir+base=$dir_plus_base\n";
354     &backup_hierarchy($prefix, $number, $upper_dir, $dir_plus_base);
355   }
356 }
357
358 # gets the number out of the file specified by a basename.  the number file
359 # is assumed to be stored in the TMP directory and to have an extension of
360 # ".num".
361 sub retrieve_number {
362   local($number_prefix) = @_;
363   # get number from the file specified and increment it for the next use.
364   local($NUMBER_FILE) = $TMP."/$number_prefix.num";
365   local($number) = &get_number($NUMBER_FILE);
366   &next_number($NUMBER_FILE);
367   return $number;
368 }
369
370 # takes a name to use as the basename for a number file, and stores the
371 # file into the archive specified.
372 sub backup_number {
373   local($number_prefix, $snarf_prefix, $number) = @_;
374 #print "backup_number: parms are: numpref=$number_prefix, archpref=$snarf_prefix, num=$number.\n";
375   local($target_file) = $original_path ."/". $snarf_prefix . "_" . $number . ".tar";
376   local($number_file) = $number_prefix . ".num";
377
378   local($currdir) = cwd();
379   chdir($TMP);
380
381   local($outcome) = 0xff & system $tar_tool, "-cf",
382       &canonicalize($target_file), &canonicalize($number_file);
383   if ($outcome) { die("failure to archive"); }
384
385   local($prefix_file) = "prefix.bac";
386   open(NUM_PREFIX, ">" . $prefix_file);
387   print NUM_PREFIX $number_prefix;
388   close(NUM_PREFIX);
389
390   $outcome = 0xff & system $tar_tool, "-rf",
391       &canonicalize($target_file), &canonicalize($prefix_file);
392   if ($outcome) { die("failure to archive"); }
393   unlink($prefix_file);
394   chdir($currdir);
395 }
396
397 # takes a prefix for the number file and a filename where it can be found.
398 # the current number in the temporary directory is compared against the file,
399 # and the new number's used if it's greater.
400 sub restore_number {
401   local($number_prefix, $number_file) = @_;
402 #print "restore num has numpref $number_prefix and numfile $number_file\n";
403   local($comparison_file) = "$TMP" . "/" . $number_prefix . ".num";
404   local($number) = &get_number($number_file);
405   local($old_number) = &get_number($comparison_file);
406   if ($number > $old_number) {
407     &store_number($number, $comparison_file);
408   }
409   unlink($number_file);
410 }
411
412 # ensures that the special restoration program is used on the archives by
413 # renaming their extension.
414 sub rename_archive {
415   local($filename) = @_;
416 #print "rename_archive: file=$filename\n";
417   &finalize_snarf($filename);
418   local(@pieces) = split(/\.[^.]*$/, $filename, 3);
419   local($just_dir_and_base) = $pieces[0];
420   local($new_name) = $just_dir_and_base . '.snarf'; 
421   rename($filename . ".gz", $new_name)
422       || die("could not rename $filename to $new_name.");
423 }
424
425 # undoes a snarfed up archive and pulls out the number.
426 sub restore_archive {
427   local($filename) = &canonicalize(&remove_trailing_slashes(@_));
428   local(@split_name) = &split_filename($filename);
429   if ($#split_name < 1) {
430     print "The name \"$filename\" could not be parsed for restoration.\n";
431     exit 1;
432   }
433   # get the basename of the file.
434   local(@pieces) = split(/\.[^.]*$/, @split_name[1], 2);
435   # we don't want the extension.
436   local($just_dir_and_base) = $split_name[0] . $pieces[0];
437   # now just get the basename without a directory.
438   local(@name_components) = split(/\//, $just_dir_and_base);
439   local($basename) = $name_components[$#name_components];
440   local($new_dir_name) = 'snarf_' . $basename;
441
442   local($currdir) = cwd();
443
444   if (!chdir($new_dir_name)) {
445     mkdir($new_dir_name, 0777)
446         || die("could not create directory $new_dir_name.");
447     if (!chdir($new_dir_name)) {
448       die("could not change to directory $new_dir_name.");
449     }
450   }
451
452   # patch a relative path name to reflect the fact that we're now underneath
453   # the directory where we were.
454   if (! ($filename =~ /^\//) 
455       && ! ($filename =~ /^.:/) ) {
456     $filename = "../" . $filename;
457   }
458
459   local($outcome) = 0xff & system $tar_tool, "-xzf",
460       &canonicalize($filename);
461   if ($outcome) { die("failure to undo archive"); }
462
463   local($outcome) =
464       0xff & system "bash", "$FEISTY_MEOW_SCRIPTS/security/normal_perm.sh", ".";
465   if ($outcome) { die("failure to normalize permissions"); }
466
467   # remove any links that might have crept in; these can cause mischief.
468   local($outcome) = 0xff & system("$find_tool . -type l -exec rm {} ';'");
469
470   # read the name of the prefix file.
471   local($prefix_file) = "prefix.bac";
472   open(NUM_PREFIX, "<" . $prefix_file);
473   local($number_prefix) = <NUM_PREFIX>;
474   close(NUM_PREFIX);
475
476   &restore_number($number_prefix, $number_prefix . ".num");
477   unlink($prefix_file);
478
479   chdir($currdir);
480 }
481
482 1;
483