#!/home/product/code/webui-perl/bin/perl -T -I /home/product/code/firmware/current/lib/perl5
#SUDOER_USERS: nobody
#SUDOER_RUNAS_USERS: root, mta
#SUDOER_TAGS: NOPASSWD, NOEXEC
use strict;
use warnings;
use Barracuda::Sudo::Lib;

=pod

=head1 NAME

add_feature

=head1 DESCRIPTION

The script copy/remove a feature script from /etc/barracuda/features

=cut

use Fcntl;
use Cwd;
my $mode = "";

my ($t, $target_name, $source_name) = get_argv(
    sub {my $opt = shift; if ($opt !~ qr/add|remove/){	return 0;} $mode = $opt; return 1;},
    qr|^[\w-]+$|,
    sub{my $name = shift; if ($mode eq 'add'){return ($name =~ /^[\w-]*$/);} elsif ($mode eq 'remove') {return ($name eq '');}else {return 0;}}); 

my $cwd = getcwd();
#untaint cwd
$cwd = $1 if $cwd =~ /^(.*)$/;


if ($mode eq "add"){
    #Create features directory if not exists
    my $dh = open_hardlink_path("/etc/barracuda", O_DIRECTORY);
    chdir $dh;
    close $dh;
    mkdir("features", 0755);
    my $source;
    if ($source_name){
	$source = Barracuda::Sudo::SafeOpen::safe_open('/home/product/code/firmware/current/bin/features/'.$source_name, 
		Barracuda::Sudo::SafeOpen::get_default_product_validator(), O_RDONLY);
    }
    my $target = Barracuda::Sudo::Lib::open_hardlink_path('/etc/barracuda/features/'.$target_name, (O_RDWR | O_EXCL | O_CREAT));
    #if script source exists then copy source to directory. Otherwise create an empy file.
    if (defined $source)
    {
   	my @source_stat  = stat($source);
	chmod ($source_stat[2], $target);
	#It would be better using IO::SendFile  ...
        while (0 < read $source, my $buff, 4096){
            print $target $buff;
        }
        close $source;	
    }
    else {
	    chmod (0755, $target);
    }
    close $target;
    chdir $cwd;
}
elsif ($mode eq "remove")
{
    my $dh = open_hardlink_path("/etc/barracuda/features", O_DIRECTORY);
    chdir $dh;
    unlink($target_name);
    close $dh; 
    chdir $cwd;
}
else
{
    failwith (250, "Unkownk command");
}

