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