#!/home/product/code/webui-perl/bin/perl -I /home/product/code/firmware/current/lib/perl5
#
# config_read - get a variable out of the config
#
use strict;
use warnings;

# Please increment as appropriate according to ISO 8601 Date syntax plus
# trailing patch, YYYYMMDDPP. The version must expand to an integer for easy
# comparison from within a shell and other environments.
use constant VERSION            => 2012073101;


use Barracuda::Environment;
use Barracuda::Config;

use DBI;
use Getopt::Long qw(:config gnu_getopt);
use List::MoreUtils qw(true);

use MS_variable;
require Barracuda::Encrypt;


my $scope = undef;
my $scope_data = '';
my $list;
my $help;


sub usage {
    (my $basename = $0) =~ s/^.*\///;
    my $usage;

    $usage = "Usage: $basename [-l] [-u user|--domain domain] variable [variable ...]\n"
           . "  -l, --list       Force output in list form\n"
           . "  -s, --scope      Read variables for given scope (user is scope data)\n"
           . "  -u, --user=USER  Scope Data from config\n"
           . "  --domain=DOMAIN  Scope Data from config\n"
           . "  -h, --help       Print usage help\n"
           . "\n"
           . "Report bugs to Zach Levow <zlevow\@barracudanetworks.com>\n";

    return $usage;
} # &usage


sub islist {
    my $name	= shift; 

    return 1 if defined $list;

    if (defined $MS_variable::variable{$name}
    && (defined $MS_variable::variable{$name}{list})
    && ($MS_variable::variable{$name}{list})) {
        return 1;
    }

    return 0;
} # &islist


sub tolist {
    my $value = defined($_[0]) ? $_[0] : ''; # Always returns at least one undefined entry
    my @values;

    return () unless $value ne '';

    @values = split(/\n/, $value . "\n~"); # Add a suffix to force split
                                           # to include trailing empty
                                           # elements.

    pop @values; # Exclude our suffix.

    return @values;
} # &tolist


my ($user, $domain);
my $result = GetOptions (
	"l|list" => \$list,
	"s|scope=s" => \$scope,
	"u|user=s" => \$user,
	"domain=s" => \$domain,
	"h|help|?" => \$help,
);

if (defined $help || !$ARGV[0]) {
    print STDERR &usage;
    exit 1;
}

if (true(sub { defined($_) }, ($scope, $user, $domain)) > 1) {
	print STDERR "The --user, --domain, and --scope options are mutually exclusive.\n";
	exit 1;
}
elsif ($user) {
	$scope = 'user';
	$scope_data = $user;
}
elsif ($domain) {
	$scope = 'domain';
	$scope_data = $domain;
}


my $dbh = Barracuda::Config::open_db();

if (!$dbh) {
    print STDERR "Unable to connect to database\n";
    exit 1;
}

# replace "*" with "%" and "?" with "_"
$scope_data =~ tr/*?/%_/;

map(tr/*?/%_/, @ARGV);

print STDERR "Looking up variables ('".join("','", @ARGV)."')".($scope ? " for $scope: $scope_data" : "")."\n";

my $scope_query = '';
if ($scope) {
    $scope_query .= " scope LIKE '$scope' AND ";
}
if ($scope_data) {
    $scope_query .= " scope_data LIKE '$scope_data' AND ";
}

my $query = qq|
SELECT
    *
FROM
    config.config
WHERE
    $scope_query
    variable LIKE ?
|;

my @results;
my %width = (
    scope      => length('Scope'),
    scope_data => length('Scope Data'),
    variable   => length('Variable'),
    value      => length('Value'),
    deleted    => length('Deleted'),
);

foreach my $variable (@ARGV) {
    my $sth = $dbh->prepare($query);
    $sth->execute($variable);
    if ($sth->rows) {
        while (my $config_hashref = $sth->fetchrow_hashref) {
            foreach my $field (keys (%$config_hashref)) {
                my $len = 0;

                if (defined $config_hashref->{$field}) {
                    if ($field eq 'variable' && &islist($config_hashref->{$field})) {
                        $len = length($config_hashref->{$field}) + length('[NN]');
                    } elsif ($field eq 'value' && $config_hashref->{value} =~ /\n/)  {
                        my @values = split(/\n/, $config_hashref->{value});
                        foreach my $value (@values) {
                            my $templen = length($value);
                            if ($templen > $len) {
                                $len = $templen;
                            }
                        }
                    } else {
                        $len = length($config_hashref->{$field});
                    }
		}

                if (!exists $width{$field} || $len > $width{$field}) {
                    $width{$field} = $len;
                }
            } # foreach $field
            push (@results, $config_hashref);
        }
    }
    $sth->finish;
}

$dbh->disconnect;

printf "+-".('-' x $width{scope}) ."-+-".('-' x $width{scope_data}) ."-+-". ('-' x $width{variable}) ."-+-". ('-' x $width{value})."-+-". ('-' x $width{deleted})."-+\n";
printf "| %-$width{scope}s | %-$width{scope_data}s | %-$width{variable}s | %-$width{value}s | %-$width{deleted}s |\n", 'Scope', 'Scope Data', 'Variable', 'Value', 'Deleted';
printf "+-".('-' x $width{scope}) ."-+-".('-' x $width{scope_data}) ."-+-". ('-' x $width{variable}) ."-+-". ('-' x $width{value})."-+-". ('-' x $width{deleted})."-+\n";

foreach my $config_hashref (@results) {
    my ($islist, @values);

    $config_hashref->{deleted} = 0 unless defined $config_hashref->{deleted};

    $config_hashref->{value} = '' unless defined $config_hashref->{value};

    if (&islist($config_hashref->{variable})) {
        $config_hashref->{scope_data} = '' if !defined $config_hashref->{scope_data};

        @values = &tolist($config_hashref->{value});

        foreach my $i (0 .. scalar @values - 1) {
            my $value = (defined $values[$i]) ? $values[$i] : '';

            # decrypt variables that are store_encrypted
            if ($MS_variable::variable{$config_hashref->{variable}}{store_encrypted}) {
                my $enc_value = new Barracuda::Encrypt($value);
                $value = $enc_value->decrypt();
            }

            printf "| %-$width{scope}s | %-$width{scope_data}s | %-$width{variable}s | %-$width{value}s | %-$width{deleted}s | \n", $$config_hashref{scope}, $$config_hashref{scope_data}, $$config_hashref{variable} . "[$i]", $value, $$config_hashref{deleted};
        }
    } elsif ($config_hashref->{value} =~ /\n/) {
        # -1 makes shift keep empty trailing fields (like empty line after last \n)
        @values = split(/\n/, $config_hashref->{value}, -1);

        my $value = (defined $values[0]) ? $values[0] : '';
        printf "| %-$width{scope}s | %-$width{scope_data}s | %-$width{variable}s | %-$width{value}s | %-$width{deleted}s | \n", $$config_hashref{scope}, $$config_hashref{scope_data}, $$config_hashref{variable}, $value, $$config_hashref{deleted};

        foreach my $i (1 .. scalar @values - 1) {
            my $value = (defined $values[$i]) ? $values[$i] : '';

            # store_encrypted: shouldn't result in nonlist values with \n
            # so we shouldn't have to decrypt

            printf "| %-$width{scope}s | %-$width{scope_data}s | %-$width{variable}s | %-$width{value}s | %-$width{deleted}s | \n", '', '', '', $value, '';
        }
    } else {
        # decrypt variables that are store_encrypted
        if ($MS_variable::variable{$config_hashref->{variable}}{store_encrypted}) {
            my $enc_value = new Barracuda::Encrypt($config_hashref->{value});
            $config_hashref->{value} = $enc_value->decrypt();
        }

        printf "| %-$width{scope}s | %-$width{scope_data}s | %-$width{variable}s | %-$width{value}s | %-$width{deleted}s | \n", $$config_hashref{scope}, $$config_hashref{scope_data}, $$config_hashref{variable}, $$config_hashref{value}, $$config_hashref{deleted};
    }
}

printf "+-".('-' x $width{scope}) ."-+-".('-' x $width{scope_data}) ."-+-". ('-' x $width{variable}) ."-+-". ('-' x $width{value})."-+-". ('-' x $width{deleted})."-+\n";
    
exit 0;
