#!/home/product/code/webui-perl/bin/perl
#
# Configure a Barracuda (firmware >= 3.1.07) to receive updates via a proxy
# Usage:  config_proxy <user>:<password>@<host>:<port>
# If no args, then list the relevant config variables

use strict;
use Barracuda::Environment;

my $me = $0;
$me =~ s#.*/##;
my $proxy_str = shift;
my $user;
my $password;
my $host;
my $port;

chomp($proxy_str);

&usage unless ($proxy_str);

if ($proxy_str eq 'default') {
    `config_change update_proxy_user '' 2>/dev/null`;
    `config_change update_proxy_password '' 2>/dev/null`;
    `config_change update_proxy_host '' 2>/dev/null`;
    `config_change update_proxy_port '' 2>/dev/null`;
    `config_change update_url '' 2>/dev/null`;
    `config_change update_method get 2>/dev/null`;
    `config_change update_receive_mode body 2>/dev/null`;

    # Save changes
    `$Barracuda::Environment::path_home/code/firmware/current/web/cgi-bin/index.cgi reload 2>/dev/null`;

    print STDERR `config_read 'update_*' 2>/dev/null`;
    exit 0;
}

if ($proxy_str eq 'noproxy') {
    ### Do nothing ###
} elsif ($proxy_str =~ /^(?:([^:\@]+)(?::([^\@]+))?\@)?([^:]+)(?::(\d+))?/) {
    $user = $1;
    $password = $2;
    $host = $3;
    $port = $4;
}
print STDERR "\$user = '$user', \$password = '$password', \$host = '$host', \$port = '$port'\n";

`config_change update_proxy_user '$user' 2>/dev/null`;
`config_change update_proxy_password '$password' 2>/dev/null`;
`config_change update_proxy_host '$host' 2>/dev/null`;
`config_change update_proxy_port '$port' 2>/dev/null`;

`config_change update_url '' 2>/dev/null`;
`config_change update_method get 2>/dev/null`;
`config_change update_receive_mode body 2>/dev/null`;

# Save changes
`$Barracuda::Environment::path_home/code/firmware/current/web/cgi-bin/index.cgi reload`;

print STDERR `config_read 'update_*'`;


sub usage {
    foreach (@_) {
	print STDERR "$_\n";
    }
    my $syntax = '[user[:password]@]host[:port]';

    print STDERR << "__USAGE__";

To configure this Barracuda for use with a proxy server:

Usage:	$me $syntax |
	$me default |
	$me noproxy

    $me default
	restores all proxy config settings to their defaults

    $me noproxy
	configures update to use a proxy-friendly URL,
	send args via POST method and receive version info
	in the HTML body but does not specify a proxy server

Current update configuration is as follows:

__USAGE__

    print STDERR `config_read 'update_*'`;
    exit 1;
}  ## usage() ##
