added missing 3rdparty and example_apps
[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 = ("*~", "*.$$$", "*.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 "-follow" "-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
231 #hmmm: trying to dereference symbolic links and stop missing stuff.
232 "-h",
233         @extra_flags, 
234 "-rf", &canonicalize($target_file), @excludes, $i;
235     if ($outcome) { die("failure to archive"); }
236   }
237   chdir("$currdir");
238 }
239
240 # backup some specific files.
241 sub backup_files {
242   local($prefix, $number, $root, $subdir, @files) = @_;
243 #print "backup_files: ref=$prefix, num=$number, subdir=$subdir, list of files=@files\n";
244   foreach $i (@files) {
245     local($new_path) = $subdir . "/" . $i;
246     if ($subdir eq ".") { $new_path = "$i"; }
247     &snarf_file_list($prefix, $number, $root, $new_path);
248   }
249 }
250
251 # backup some specific directories.
252 sub backup_directories {
253   local($prefix, $number, $root, $subdir, @dirs) = @_;
254 #print "backup_directories: ref=$prefix, num=$number, root=$root, subdir=$subdir, list of dirs=@dirs.\n";
255   foreach $i (@dirs) {
256     local($path_to_use) = $subdir . "/" . $i;
257     if ($i eq ".") {
258       $path_to_use = $subdir;
259     }
260     &snarfer($prefix, $number, $root, $path_to_use, ("-maxdepth", "1"));
261   }
262 }
263
264 # removes items from the file that match a pattern.
265 sub remove_from_backup {
266   local($prefix, $number, $pattern) = @_;
267 #print "remove_from_backup: pref=$prefix, num=$number, patt=$pattern,\n";
268   local($target_file) = &snarf_name($prefix, $number);
269
270   open(TARPROC, "$tar_tool --delete -f " . &canonicalize($target_file)
271       . " \"$pattern\" 2>$null_log |");
272   <TARPROC>;
273 }
274
275 # recursively scoops up a directory hierarchy.
276 sub backup_hierarchy {
277   local($prefix, $number, $root, $filepart) = @_;
278 #print "backup_hierarchy: pref=$prefix, num=$number, root=$root, filepart=$filepart\n";
279   local(@locus_temp) = &glob_list($root);
280   local($save_root) = $root;
281   local($root) = $locus_temp[0];
282   if (!length($root)) {
283     local($base) = $save_root . "/" . $filepart;
284 #print "adding to missing in backup_hierarchy A: $base\n";
285     push(@missing_log, $base);
286     return;
287   }
288   local($new_pattern) = "$root/$filepart";
289   if ($root =~ /\/$/) { $new_pattern = "$root$filepart"; }
290   local(@mod_locus) = &glob_list($new_pattern);
291   if (!scalar(@mod_locus)) {
292     local($base) = &basename($root . "/" . $filepart);
293 #print "adding to missing in backup_hierarchy B: $base\n";
294     push(@missing_log, $base);
295   } else {
296     foreach $i (@mod_locus) {
297       local($new_locus) = $root;
298       local $offset_len = length($root) + 1;
299       local $char_len = length($i) - length($root) - 1;
300       # make sure we don't double slashes up if one's already there.
301       if ($root =~ /\/$/) { $offset_len--; $char_len++; }
302       local($extra_portion) = substr $i, $offset_len, $char_len;
303       if (!length($extra_portion)) {
304         # well, in this case, there's nothing left of the extra part after
305         # the root.  we'll push the last component of the root down into
306         # the extra part so there's actually something to traverse.
307         $new_locus = &dirname($root);
308         $extra_portion = &basename($root);
309       }
310       &snarfer($prefix, $number, $new_locus, $extra_portion, ());
311     }
312   }
313 }
314
315 # recursively scoop up a list of directory hierarchies.
316 sub backup_hierarchies {
317   local($prefix, $number, $root, @dirs) = @_;
318 #  print "backup_hierarchy: pref=$prefix, num=$number, root=$root,\n";
319 #  print "list of dirs=@dirs.\n";
320   foreach $i (@dirs) {
321     &backup_hierarchy($prefix, $number, $root, $i);
322   }
323 }
324
325 # grab up all the files in a directory (second parm) that are named matching
326 # a simple text pattern (third parm).  if there is a fourth parameter, it is
327 # used as an extra directory component after the main directory.
328 sub snarf_by_pattern {
329   local($prefix, $dir, $pattern, $extra_component) = @_;
330   local($had_extra) = length($extra_component) != 0;
331 #print "snarf by pattern, dir = $dir, patt = $pattern, extra = $extra_component\n";
332   if ($had_extra) {
333     $dir = "$dir/$extra_component";
334   }
335   @dir_contents = &glob_list("$dir/*$pattern*"); 
336 #print "dir contents: @dir_contents\n";
337
338   if (!scalar(@dir_contents)) {
339     print "no '$pattern' directores were backed up in $dir.\n";
340   }
341   
342   foreach $item (@dir_contents) {
343     if ( ($item =~ /$pattern.*snarf/) || ($item =~ /$pattern.*tar/) ) { next; }
344     if ( ! -d "$item" ) { next; }
345 #print "now really planning to backup hier of $item\n";
346     # normal backup had no extra component.
347     local $upper_dir = &dirname($item);
348     local $dir_plus_base = &basename($item);
349     # if we did have an extra component, we do this a bit differently.
350     if ($had_extra) {
351       $upper_dir = &dirname( &dirname($item) );
352       $dir_plus_base = &basename( &dirname($item) ) . "/" . &basename($item);
353     }
354 #print "using upper=$upper_dir and dir+base=$dir_plus_base\n";
355     &backup_hierarchy($prefix, $number, $upper_dir, $dir_plus_base);
356   }
357 }
358
359 # gets the number out of the file specified by a basename.  the number file
360 # is assumed to be stored in the TMP directory and to have an extension of
361 # ".num".
362 sub retrieve_number {
363   local($number_prefix) = @_;
364   # get number from the file specified and increment it for the next use.
365   local($NUMBER_FILE) = $TMP."/$number_prefix.num";
366   local($number) = &get_number($NUMBER_FILE);
367   &next_number($NUMBER_FILE);
368   return $number;
369 }
370
371 # takes a name to use as the basename for a number file, and stores the
372 # file into the archive specified.
373 sub backup_number {
374   local($number_prefix, $snarf_prefix, $number) = @_;
375 #print "backup_number: parms are: numpref=$number_prefix, archpref=$snarf_prefix, num=$number.\n";
376   local($target_file) = $original_path ."/". $snarf_prefix . "_" . $number . ".tar";
377   local($number_file) = $number_prefix . ".num";
378
379   local($currdir) = cwd();
380   chdir($TMP);
381
382   local($outcome) = 0xff & system $tar_tool, "-cf",
383       &canonicalize($target_file), &canonicalize($number_file);
384   if ($outcome) { die("failure to archive"); }
385
386   local($prefix_file) = "prefix.bac";
387   open(NUM_PREFIX, ">" . $prefix_file);
388   print NUM_PREFIX $number_prefix;
389   close(NUM_PREFIX);
390
391   $outcome = 0xff & system $tar_tool, 
392
393 #hmmm: trying to dereference symbolic links and stop missing stuff.
394 "-h",
395
396 "-rf",
397       &canonicalize($target_file), &canonicalize($prefix_file);
398   if ($outcome) { die("failure to archive"); }
399   unlink($prefix_file);
400   chdir($currdir);
401 }
402
403 # takes a prefix for the number file and a filename where it can be found.
404 # the current number in the temporary directory is compared against the file,
405 # and the new number's used if it's greater.
406 sub restore_number {
407   local($number_prefix, $number_file) = @_;
408 #print "restore num has numpref $number_prefix and numfile $number_file\n";
409   local($comparison_file) = "$TMP" . "/" . $number_prefix . ".num";
410   local($number) = &get_number($number_file);
411   local($old_number) = &get_number($comparison_file);
412   if ($number > $old_number) {
413     &store_number($number, $comparison_file);
414   }
415   unlink($number_file);
416 }
417
418 # ensures that the special restoration program is used on the archives by
419 # renaming their extension.
420 sub rename_archive {
421   local($filename) = @_;
422 #print "rename_archive: file=$filename\n";
423   &finalize_snarf($filename);
424   local(@pieces) = split(/\.[^.]*$/, $filename, 3);
425   local($just_dir_and_base) = $pieces[0];
426   local($new_name) = $just_dir_and_base . '.snarf'; 
427   rename($filename . ".gz", $new_name)
428       || die("could not rename $filename to $new_name.");
429 }
430
431 # undoes a snarfed up archive and pulls out the number.
432 sub restore_archive {
433   local($filename) = &canonicalize(&remove_trailing_slashes(@_));
434   local(@split_name) = &split_filename($filename);
435   if ($#split_name < 1) {
436     print "The name \"$filename\" could not be parsed for restoration.\n";
437     exit 1;
438   }
439   # get the basename of the file.
440   local(@pieces) = split(/\.[^.]*$/, @split_name[1], 2);
441   # we don't want the extension.
442   local($just_dir_and_base) = $split_name[0] . $pieces[0];
443   # now just get the basename without a directory.
444   local(@name_components) = split(/\//, $just_dir_and_base);
445   local($basename) = $name_components[$#name_components];
446   local($new_dir_name) = 'snarf_' . $basename;
447
448   local($currdir) = cwd();
449
450   if (!chdir($new_dir_name)) {
451     mkdir($new_dir_name, 0777)
452         || die("could not create directory $new_dir_name.");
453     if (!chdir($new_dir_name)) {
454       die("could not change to directory $new_dir_name.");
455     }
456   }
457
458   # patch a relative path name to reflect the fact that we're now underneath
459   # the directory where we were.
460   if (! ($filename =~ /^\//) 
461       && ! ($filename =~ /^.:/) ) {
462     $filename = "../" . $filename;
463   }
464
465   local($outcome) = 0xff & system $tar_tool, "-xzf",
466       &canonicalize($filename);
467   if ($outcome) { die("failure to undo archive"); }
468
469   local($outcome) =
470       0xff & system "bash", "$FEISTY_MEOW_SCRIPTS/security/normal_perm.sh", ".";
471   if ($outcome) { die("failure to normalize permissions"); }
472
473   # remove any links that might have crept in; these can cause mischief.
474   local($outcome) = 0xff & system("$find_tool . -type l -exec rm {} ';'");
475
476   # read the name of the prefix file.
477   local($prefix_file) = "prefix.bac";
478   open(NUM_PREFIX, "<" . $prefix_file);
479   local($number_prefix) = <NUM_PREFIX>;
480   close(NUM_PREFIX);
481
482   &restore_number($number_prefix, $number_prefix . ".num");
483   unlink($prefix_file);
484
485   chdir($currdir);
486 }
487
488 1;
489