#!/usr/bin/perl -w
use strict;
use File::Basename;
# ----------------------------- Config -----------------------------
my $ftpsfv = "/usr/bin/ftpsfv";
	# path to ftpsfv
my $sitename = "SFV";
	# site-name
my $tmpfile = ".tmp";
	# tmp-filename ftpsfv uses, ftpsfv will append the name of the checked
	# sfv file without .sfv
my $user = "";					
my $group = "";
	# user and group to which belong the created files & dirs, default
	# the user/group which runs ftpsfv e.g. the user/root defined in
	# the ftpexecd config file
	# Setting the user will only work, if ftpsfv is called from ftpexecd
	# running as root:root
	# It's better not to use this option and set the ownership of the
	# files/dirs via the user/group context of ftpexecd for security
	# reasons.
my $file_permissions = "0777";			
	# the permissions for the files created
my $dir_permissions = "0777";			
	# the permissions for the directories created
my $check_only_first_sfv_found = 1;		
	# if set to 1 ftpsfv will only check the first .sfv file found
	# if set to 0 all .sfv files in the current dir will be checked
	# on normal case every sfv release is it's own dir, so a value
	# of 1 is ok...
my @exclude_dirs = ("");
	# this sets the dirs in which no sfv checking is performed
	# example:
	# my @exclude_dirs = ("/ftp/dir1",
	#		      "/ftp/dir2",
	#		      etc..);
my $path = "";
my @filenames;
# ----------------------------- Program -----------------------------
if (!@ARGV || $#ARGV != 0)
{
    print("Usage: ftpsfvcheck.pl filename\n");
    exit(-1);
}
$path = dirname($ARGV[0]);
if ($#exclude_dirs >= 0)
{
    my $found = 0;
    foreach my $dir (@exclude_dirs)
    {
	if ($dir eq $path)
	{
	    $found = 1;
	    last;
	}
    }
    if ($found)
    {
	print($path . " is in excluded directories.\n");
	exit(-2);
    }
}
chdir($path) or die "Can't open directory ".$path."\n";
opendir(DIR, $path) or die "Can't read content from directory ".$path."\n";
@filenames = sort(grep(/\.sfv$/mi, readdir(DIR)));
closedir(DIR) or die "Can't close directory ".$path."\n";
if (@filenames)
{
    foreach my $filename (@filenames) 
    {
	if ($filename =~ /^[^\r\n]*\.sfv$/si)
	{
	    system($ftpsfv,
		   "-s", $sitename,
		   "-t", $tmpfile,
		   "-u", $user,
		   "-g", $group,
		   "-f", $file_permissions,
		   "-d", $dir_permissions,
		   "${path}/${filename}"
		  );
	    if ($check_only_first_sfv_found)
	    {
		last;
	    }
	}
    }
}
exit(0);