#!/home/product/code/webui-perl/bin/perl

=head1 NAME

feature_read - Read about available features on this device

=head1 SYNOPSIS

    feature_read
    feature_read [--debug] someFeature

=head1 DESCRIPTION

This is a simple utility to get available feature information for
this appliance.  It uses Barracuda::Utils and
Barracuda::Feature_table to do this.

The tool fakes (in an unbelievably lame fashion) a wildcard syntax
similar to config_read for convenience.

=head1 AUTHOR

B.J. Black <bblack@barracuda.com>

=cut

use strict;
use lib '/home/product/code/firmware/current/lib/perl5';
use Barracuda::Utils;
use Barracuda::Feature_table;
use MS_config;
use Getopt::Long;

# Used instead of e.g. Data::Dumper because I wanted a bit of a tighter
# format.
#
# printable($refOrScalar)
#
# Recursive.  Returns a reasonable printable version of whatever ref
# was passed in.
#
# Doesn't cope with non scalar/arrayref/hashrefs well
#
sub printable {
	my $val = shift;
	my $pval = "[Object]";
	if( !ref($val) ) {
		$pval = $val;
	} elsif( ref($val) eq "ARRAY" ) {
		$pval = "[ " . join(", ", map( { printable($_) } @$val)) . " ]";
	} elsif( ref($val) eq "HASH" ) {
		$pval = "{ " . join(", ", map( { "$_ => " . printable($val->{$_}) } sort(keys(%$val)))) . " }";
	}
	return $pval;
}

my $debug = 0;
my $help = 0;
my $overrides_file = "/home/product/code/config/overrides.conf";
our %feature_overrides;

GetOptions(
	"debug" => \$debug,
	"help" => \$help,
);
if( $help ) {
	system("perldoc", $0);
	exit(0);
}
# Chew on command-line params.  Regexes fake the SQL wildcard behavior of
# config_read for convenience.
my $param = shift(@ARGV);
$param =~ s/\*/.*/g;
$param =~ s/%/.*/g;
$param = ".*" if !$param;

my $overrides = "";
if( -f $overrides_file ) {
	print "Loading overrides file $overrides_file...\n" if $debug;
	open IN, $overrides_file;
	while( my $line = <IN> ) {
		$overrides .= $line;
	}
	close IN;
	eval($overrides);
}

if( defined( %feature_overrides ) ) {
	print "Feature Overrides:\n" if $debug;
	while( my ($k, $v) = each(%feature_overrides) ) {
		print "    $k = $v\n" if $debug;
	}
}
print "Looking for \"$param\"\n" if $debug;

# Get the model and print out
my $model = MS_config::get_model();
for my $i (keys(%{$Barracuda::Feature_table::feature_table{$model}})) {
	if( $i =~ /^$param$/ ) {
		my $val = $Barracuda::Feature_table::feature_table{$model}{$i};
		$val = $feature_overrides{$i} if defined($feature_overrides{$i});
		print "$i=" . printable($val) . "\n";
	}
}
