#
# usage - vault_file_cp(file2cp, location_dir)
#

require "conf/coroner.cf";
require "$LIB/realpath.pl";

sub vault_file_cp {
local($file) = @_;
local($realfile, $symlink);

$realfile = &realpath($file);

print "vault cp $file ... $realfile\n" if $debug;

$symlink = "";

# sym link?
if ($realfile ne $file) {
	$symlink = $file;
	$file = $realfile;
	}

# bad stuff...
return if -d $file;
return if (-S $file || -p $file);
return if (-b $file || -c $file);

&make_vault_dir($file);
&make_vault_dir($symlink) if $symlink;

#
# strip off the first slash; we'll use that for a relative
# path in the HTML file below...
#
($file2 = $file) =~ s@/@@;
$symlink =~ s@/@@;

# $resting_place = "$DATA/$conf_vault/$path2file";
$resting_place = "$DATA/$conf_vault/$file2";

# don't need to copy it twice...
next if -f "$DATA/$conf_vault/$file2";

# don't need any dirs slipping in here... file also needs
# to exist to copy ;-)
next if -d $file || ! -f $file;

print "cp $file $resting_place\n" if $debug;
&execute_command($CP, $file, $resting_place);

if ($symlink) {
	# print "cp $file $resting_place\n";
	# print "$DATA/$conf_vault/$file2, $symlink\n";

	print "$DATA/$conf_vault/$file2, $symlink\n" if $debug;
	symlink("$DATA/$conf_vault/$file2", "$DATA/$conf_vault/$symlink");
	}

#
# update HTML file
#
die "Can't open configuration vault HTML index file $DATA/$conf_vault/index.html\n" unless open(CFI, ">>$DATA/$conf_vault/index.html");
 
# print CFI "<TR><TD><pre><a href=\"$file2\">$file</pre></a></TD><TD><pre>$ls</pre></TD></TR>\n";
print CFI "<a href=\"$file2\">$file</pre></a>\n";

close(CFI);

}

#
# we can't do "mkdir -p /usr/foo/bar/baz", so we have to
# loop through each thing and make a dir.
#
sub make_vault_dir {
local($file) = @_;

print "putting $file into vault\n" if $debug;

print "putting $file into vault\n" if $verbose;

$resu = (@path2file) = split(/\//, $file);
$path2file = "";

pop(@path2file);
for (@path2file) {
	next unless $_;
	$path2file = "$path2file/$_";
	print "$file - $path2file\n" if $debug;

	# don't need to make it twice...
	next if -d "$DATA/$conf_vault/$path2file";

	print "mkdir $DATA/$conf_vault/$path2file\n"
		if $debug;

	mkdir("$DATA/$conf_vault/$path2file", 0700);
	}

}

1;
