#!perl

use strict;
use warnings;

use File::Util;
use File::Copy;
use Archive::Tar;
use CGI;
use Template;
use CGI::Carp qw(fatalsToBrowser);

use TCE::Config;


our $msg_ok = $TCE::Config::MSG_SYMBOLS{'ok'};
our $msg_fail = $TCE::Config::MSG_SYMBOLS{'fail'};
our $msg_warn = $TCE::Config::MSG_SYMBOLS{'warn'};

our @messages = ();
our $go = 1;

# create the CGI object
my $cgi = CGI->new();

# create the File::Utils object
my $fu = File::Util->new();

# create the tar object
my $tar = Archive::Tar->new();

# get the directory name (use cgi)
my $item = $cgi->param('itemid') || undef;
my $name = substr($item,0,index($item,'.'));

if ($item && (-e $TCE::Config::ARCHIVE_DIR.$item))
{
	# read the archive
	$tar->read($TCE::Config::ARCHIVE_DIR.$item);
	my @files = $tar->list_files();
	
	# test if item already exists
	my @test_path = split(/\//,$files[0]);
	unless (-e $TCE::Config::ITEMS.$test_path[$#test_path -1])
	{
		# unpack archive
		foreach my $file (@files)
		{
			my @path = split(/\//,$file);
			my $target = pop(@path);
		   	$target = pop(@path).'/'.$target;
			$tar->extract_file($file,$TCE::Config::ITEMS.$target);
			message("$msg_ok Datei $file entpackt nach $TCE::Config::ITEMS$target ");
		}
		# make a backup and remove tar from archive
		my $timestamp = time;
		move $TCE::Config::ARCHIVE_DIR.$item, $TCE::Config::ARCHIVE_BACKUP.$item.'_'.$timestamp;
		message("$msg_ok Eine Sicherheitskopie wurde unter dem Namen $TCE::Config::ARCHIVE_BACKUP$item\_$timestamp angelegt");
		message("$msg_ok Der Vorgang $name wurde wiederhergestellt.")
	}
	else
	{
		error("$msg_fail Es existiert bereits ein Vorgang mit dem Namen $item. Bitte löschen oder archivieren Sie diesen.")
	}
}
else
{
	error("$msg_fail Das Archiv $item wurde nicht gefunden.");
}

# output to browser
my $template = Template->new({'INCLUDE_PATH' => $TCE::Config::TEMPLATES_DIR});
print $cgi->header( -type=>"text/html" );
$template->process('tce_unarchive.tmpl',{'messages' => \@messages}) || die $template->error();

exit(1);
sub message
{
	my $text = shift;
	push @messages, $text;
	return 1;
}

sub error
{
	my $text = shift;
	push @messages, $text;
	$go = 0;
	return undef; 

}