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