#!/usr/bin/perl

# Note this still doesn't really undo everything.

use Getopt::Std;
use English;
use Cwd;

# Darn it Sweth -- make sure your code actually RUNS!!
##
# Define Installation Directory
#if (${PROGRAM_NAME} !~ m|^/|) {
#	my ${CUR_DIR} = cwd;
#	$GLOBAL_BDIR{"install"} = ${CUR_DIR} . '/' . ${PROGRAM_NAME};
#        # trim app name, e.g. "/foo/./bar.pl" -> "/foo/."
#	$GLOBAL_BDIR{"install"} =~ s/^(.*?)\/[^\/]*$/$1/;
	# remove trailing "/.", e.g. "/foo/." -> "/foo"
#	$GLOBAL_BDIR{"install"} =~ s:/\.$::;
#	if (! -d $GLOBAL_BDIR{"install"} ) {
#		die "Unable to determine the install directory for \"${PROGRAM_NAME}\" -- please CD to the Bastille install dir or run ${PROGRAM_NAME} with a fully qualified path.";
#	}
#} else {
	$GLOBAL_BDIR{"install"} = ${PROGRAM_NAME};
	$GLOBAL_BDIR{"install"} =~ s/^(.*?)\/[^\/]*$/$1/;
#};

### Process command-line arguments...
getopts("u:r:",\%options);

if ($options{r}) {
	$GLOBAL_PREFIX = $options{r};
} else {
	$GLOBAL_PREFIX = "";
};
   
# undo directory
if ($options{u}) {
	$GLOBAL_BDIR{"undo"} = $options{u};
} else {
	$GLOBAL_BDIR{"undo"} = "/var/log/Bastille/undo";
};

chdir $GLOBAL_BDIR{"undo"}."/backup" || die "Cannot find undo backup dir";

#mkdir "/root/bastille-undo-backup",0700;

open FILES,"find . -type f -print |";
while (my $file =<FILES>) {
	chomp $file;
	push @filelist,$file;
}
close FILES;

#Backup the bastille-modified files that undo would ordinarily be killing off.
#`/bin/tar -cvpf - @filelist | ( cd /root/bastille-undo-backup ; /bin/tar -xvpf - ) `;

# Place the original files back in place.
while (my $file = pop @filelist) {
   `/bin/mv $file /$file`;
} 

chdir $GLOBAL_BDIR{"undo"};

foreach $undoScript ( "undo-removed-symlinks", "undo-created-files", "undo-created-dirs" ) {
	if ( -f $undoScript && -x $undoScript ) {
		`./$undoScript`;
	}
}

