#!perl

use strict;
use warnings;


use Template;
use File::Util;
use CGI;
use File::Copy;

use TCE::Config;

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

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

my $item = $cgi->param('itemid') || undef;
my $restore = $cgi->param('restore') || undef;

# global variables
my @versions = ();

if ($restore && $item)
{
	my @filelist = $fu->list_dir($TCE::Config::ITEMS.'/'.$item, qw/--files-only --pattern=^struct\.dmp*/);
	if (grep($restore,@filelist))
	{
     		my $timestamp = time;
      		move $TCE::Config::ITEMS.$item.'/'.$TCE::Config::DATA_STORAGE{'struct'}, $TCE::Config::ITEMS.$item.'/'.$TCE::Config::DATA_STORAGE{'struct'}.'_'.$timestamp;
      		copy $TCE::Config::ITEMS.$item.'/'.$restore,$TCE::Config::ITEMS.$item.'/'.$TCE::Config::DATA_STORAGE{'struct'};
	}	
}

if ($item)
{
# list all existing directories in $ITEMS
my @filelist = $fu->list_dir($TCE::Config::ITEMS.'/'.$item, qw/--files-only --pattern=^struct\.dmp*/);


foreach my $file (@filelist)
{
	my ($front,$timestamp) = split(/_/,$file);
	$timestamp = time unless ($timestamp ne '');
	
	my $fileentry = {};
	   $fileentry->{'date'} = localtime($timestamp);
	   $fileentry->{'filename'} = $file;
	   $fileentry->{'timestamp'} = $timestamp;
	push @versions,$fileentry;
}

@versions = sort {$b->{'timestamp'} <=> $a->{'timestamp'}} @versions;
}

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

exit(1);