#!/home/product/code/webui-perl/bin/perl -I /home/product/code/firmware/current/lib/perl5
#
# config_change - set a variable in the config
#
# TODO: &tolist and &tostring should operate on references. Otherwise,
#       passing in and out the gigantic arrays from the gigantic blobs in
#       the database could get painfully slow.
#
use strict;
use warnings;

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

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

use Barracuda::Encrypt::Utils;
use MS_variable;
#
# Globals
#
my $scope;
my $scope_data;
my $delete;
my $list;
my $nolist;
my $index;
my $help;
my $do_encrypt;
my $no_encrypt;
my $variable;
my $value;


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

	$usage	= "Usage: $basename [-dlL] [-i index] [-u user|--domain domain] variable value\n"
		. "  -d, --delete       Delete variable\n"
		. "  -l, --list         Force variable to list form\n"
		. "  -L, --no-list      Force variable to non-list form\n" # GNU opposite syntax
		. "  -i, --index=INDEX  Positional index\n"
		. "  -u, --user=USER    Change USER's scoped variables(s)\n"
		. "  --domain=DOMAIN    Change DOMAIN's scoped variables(s)\n"
		. "  --scope=VALUE      Use SCOPE as the scope to change\n"
		. "  --scope-data=VALUE Use VALUE as the scope_data to change\n"
		. "  -e, --encrypt      Apply variable's encryption setting\n"
		. "  -E, --no-encrypt   Force --encrypt off\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; 

	#
	# Obey forced type.
	#
	if ($name eq $variable) {
		return 0 if defined $nolist;

		return 1 if defined $list;
	}

	#
	# Otherwise check the map.
	#
	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 = shift; # Always returns at least one undefined entry
	my @values;

	return () unless defined $value;

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

	pop @values; # Exclude our suffix.

	return @values;
} # &tolist


sub tostring {
	my @values = @_ or return undef;
	my $string = '';
	my $value;

	foreach $value (@values) {
		$string .= $value if defined $value;
		$string .= "\n";
	}

	chop $string;

	return $string;
} # &tostring


sub getvalue {
	my $name	= shift or return undef;
	my $scope	= shift;
	my $scope_data	= shift;
	my $dbh		= Barracuda::Config::open_db();
	my ($scope_query, $query, $sth, $row);

	return undef unless defined $dbh;

	$scope_query = (defined $scope_data)
          ? "scope = '$scope' AND scope_data LIKE '$scope_data' AND"
          : '';

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

	$sth	= $dbh->prepare($query) or return undef;

	$sth->execute($name) or return undef;

	if ($sth->rows && ($row = $sth->fetchrow_hashref)) {
		return (&islist($name))? &tolist($row->{value}) : $row->{value};
	}

	return undef;
} # &getvalue


sub indexof {
	my $name	= shift or return undef;
	my $index	= shift or return undef;

	#
	# Find the variable which defines the variables tied to itself.
	#
	foreach my $var (keys %MS_variable::variable) {
		next unless defined $MS_variable::variable{$var}->{tied_vars};
		next unless &islist($var);

		if (grep {$_ eq $name} @{$MS_variable::variable{$var}->{tied_vars}}) {
			my @values	= getvalue($var);
			my $i		= 0;

			foreach my $val (@values) {
				return $i if ($val eq $index);

				$i++;
			}
		}
	}

	return undef;
} # &indexof


#
# Parse Command Line
#
my ($user, $domain);
my $result = GetOptions (
	"u|user=s"	=> \$user,
	"domain=s"	=> \$domain,
	"scope=s"	=> \$scope,
	"scope-data=s"	=> \$scope_data,
	"d|delete"	=> \$delete,
	"l|list"	=> \$list,
	"L|no-list"	=> \$nolist,	# GNU convention is to upper case
					# the short form and prepend "no-"
					# to the long form.
	"i|index=i"	=> \$index,
	"e|encrypt"	=> \$do_encrypt,
	"E|no-encrypt"	=> \$no_encrypt,
	"h|help|?"	=> \$help
);

unless ($result) {
	print STDERR &usage;
	exit 1;
}

($variable, $value) = @ARGV;

if (defined $variable && $variable =~ /(.*)\[(\S+)\]$/) {
	if (defined $index && $index != $2) {
		print STDERR "Option -i, --index and indexed variable name mutually exclusive\n";
		print STDERR &usage;
		exit 1;
	}

	$variable	= $1;
	$index		= $2;
}

if (defined $help) {
	print STDERR &usage;
	exit 0;
}

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

if (!defined $variable) {
	print STDERR "Variable name not specified\n";
	print STDERR &usage;
	exit 1;
}

if (defined $delete && defined $value) {
	print STDERR "Cannot specify value when deleting\n";
	print STDERR &usage;
	exit 1;
}

if (!defined $delete && !defined $value) {
	print STDERR "Please specify value\n";
	print STDERR &usage;
	exit 1;
}

if (defined $list && defined $nolist) {
	print STDERR "Options -l, --list and -L, --no-list are mutually exclusive\n";
	print STDERR &usage;
	exit 1;
}

if (&islist($variable) && !defined $index) {
	print STDERR "Please specify index for list $variable, or force to non-list\n";
	print STDERR &usage;
	exit 1;
}

if (!&islist($variable) && defined $index) {
	print STDERR "Index specified for non-list variable\n";
	print STDERR &usage;
	exit 1;
}

if (defined $do_encrypt && defined $no_encrypt) {
	print STDERR "Options -e, --encrypt and -E, --no-encrypt are mutually exclusive\n";
	print STDERR &usage;
	exit 1;
}

# For backwards compatibility, encrypt is not automatically on if
# auto-detected. However, user_password was never encrypted before.
if (!$no_encrypt
      && ($do_encrypt || $variable eq 'user_password')
      && (my $encrypt_name = $MS_variable::variable{$variable}->{'encrypt'})) {
	print STDERR "Encrypting value with $encrypt_name\n";
	$value = Barracuda::Encrypt::Utils::encrypt_string($encrypt_name,
                                                           $value);
}


#
# Map magic index
#
if (defined $index && $index !~ /^\d+$/) {
	my $i	= &indexof($variable,$index);

	if (!defined $i) {
		print STDERR "Could not convert magic index of '$index'\n";
		exit 1;
	}

	$index	= $i;
}


#
# Select the existing values
#
my $query;
my @va_list;
my $dbh;
my $sth;


$dbh = Barracuda::Config::open_db() or do {
	print STDERR "Unable to connect to database: $DBI::errstr\n";
	exit 1;
};
$dbh->do("use config");

$dbh->begin_work or do {
	print STDERR "Failed to start transaction: $dbh->errstr\n";
	exit 1;
};

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

#
# XXX: The DISTINCT qualifier is a hack. The users set gives us back one row
#      for every time the username is in the database. This is joined with
#      the variable (config) set. The variable set is suitably restricted.
#      We need a way to restrict the user set directly with DISTINCT. The
#      only way to do that is with a sub-select or temporary table.
#
if (defined $scope) {
	$query = qq|
		SELECT DISTINCT	users.scope,
				users.scope_data,
				config.variable,
				config.value,
				config.deleted

		FROM		config AS users
		LEFT JOIN	config

		ON	users.scope		= config.scope
		AND	users.scope_data	= config.scope_data
		AND	config.variable		= ?

		WHERE	users.scope		= ?
		AND	users.scope_data	LIKE ?
	|;

	@va_list	= (
		$variable,
		$scope,
		$scope_data,
	);
} else {
	$query = qq|
		SELECT DISTINCT	users.scope,
				users.scope_data,
				config.variable,
				config.value,
				config.deleted

		FROM		config AS users
		LEFT JOIN	config

		ON	users.scope		= config.scope
		AND	users.scope_data	= config.scope_data
		AND	config.variable		= ?

		WHERE	users.scope		= 'global'
	|;

	@va_list	= (
		$variable
	);
} # defined $user else


$sth = $dbh->prepare($query) or do {
	print STDERR "Unable to prepare SELECT statement: $dbh->errstr\n";
	exit 1;
};

$sth->execute(@va_list) or do {
	print STDERR "Unable to execute SELECT statement: $dbh->errstr\n";
	exit 1;
};


#
# Iterate over the values, INSERTing if they aren't there and UPDATEing
# otherwise.
#
my $row;
my @updated;
my $updated;	# Updated value
my $deleted;	# Deleted status
my $naffected	= 0;
my $logmsg;

while ($row = $sth->fetchrow_hashref) {
	my $sth;	# Don't clobber our SELECT

	if (defined $value && defined $index) {
		@updated		= &tolist($row->{value});
		$updated[$index]	= $value;
		$updated		= &tostring(@updated);
		$deleted		= undef;
	} elsif (defined $value) {
		$updated	= $value;
		$deleted	= undef;
	} elsif (defined $index) {
		@updated		= &tolist($row->{value});
		splice @updated,$index,1;
		$updated		= &tostring(@updated);
		$deleted		= undef;
	} else {
		$updated	= $row->{value};
		$deleted	= 1;
	}

	if (defined $row->{variable}) {
		$query	= qq|
			UPDATE	config

			SET	value	= ?,
				deleted	= ?,
				changed	= NOW()

			WHERE	scope		= ?
			AND	scope_data	= ?
			AND	variable	= ?
		|;

		@va_list	= (
			$updated,
			$deleted,
			$row->{scope},
			$row->{scope_data},
			$row->{variable}
		);

		printf STDERR "Updating $variable for %s\n",
			($user || 'global');
	} else {
		$query	= qq|
			INSERT INTO config (
				scope,
				scope_data,
				variable,
				value,
				deleted,
				changed
			) VALUES (
				?,
				?,
				?,
				?,
				?,
				NOW()
			)
		|;

		@va_list	= (
			$row->{scope},
			$row->{scope_data},
			$variable,
			$updated,
			$deleted
		);

		printf STDERR "Inserting $variable for %s\n",
			($user || 'global');
	} # if defined $row->{variable} else

        my $var_type = MS_variable::get_value( $variable, 'type' );
        if ( defined $var_type && $var_type eq 'password' || MS_variable::get_value( $variable, 'no_log_display' ) ) {
            # Obscure sensitive entries
            $updated = "*****";
        }
        $logmsg = "$row->{scope}\[$row->{scope_data}\] CHANGE $variable ($updated)";
        Barracuda::Logging::log_msg('INFO', $logmsg);

	$sth = $dbh->prepare($query) or do {
		printf STDERR "Failed to prepare UPDATE or INSERT for %s: %s\n",
			($scope_data || 'global'),
			$dbh->errstr;
		next;
	};

	$sth->execute(@va_list) or do {
		printf STDERR "Failed to execute UPDATE or INSERT for %s: %s\n",
			($scope_data || 'global'),
			$dbh->errstr;
		next;
	};

    if (defined $row->{variable} && &islist($row->{variable})) {
        my $query	= qq|
            UPDATE config SET value='', changed=NOW()
            WHERE scope		= ?
            AND	scope_data	= ?
            AND	variable	= ?
        |;

        my $anchor = Barracuda::Config::Backend::tie_anchor_variable($row->{variable});

        my @va_list	= (
            $row->{scope},
            $row->{scope_data},
            $anchor . '__md5'
        );

        $sth = $dbh->prepare($query) or do {
            printf STDERR "Failed to prepare DELETE for %s: %s\n", ($scope_data || 'global'), $dbh->errstr;
            next;
        };

        $sth->execute(@va_list) or do {
            printf STDERR "Failed to execute DELETE for %s: %s\n", ($scope_data || 'global'), $dbh->errstr;
            next;
        };
    }

	$naffected++;
} # while $row


if ($naffected > 0) {
	$dbh->commit or do {
		print STDERR "Failed to commit transaction: $dbh->errstr\n";
		exit 1;
	};

	print STDERR "Affected $naffected rows\n";
} else {
	print STDERR "Nothing to update\n";
} # if $rows else


$dbh->disconnect or do {
	print STDERR "Failed to disconnect: $dbh->errstr\n";
	exit 1;
};

exit 0;


__DATA__


if (&islist($variable)) {
    @updated = &tolist($current);

    $updated[$index] = $value;
    $updated         = &tostring(@updated);
} else {
    $updated = $value;
}


if (&islist($variable)) {
    print STDERR "Setting variable $variable[$index] to value $value".($scope ? " for $scope: $scope_data" : "")."\n";
} else {
    print STDERR "Setting variable $variable to value $value".($scope ? " for $scope: $scope_data" : "")."\n";
}


if ($current) {
    $query = qq|
        UPDATE config
        SET value = ?,
            changed = NOW()
        WHERE
            $scope_clause
            variable = ?
    |;

} else {
    my $comment = '';

    if (defined $MS_variable::variable{$variable}
    && (defined $MS_variable::variable{$variable}{comment})) {
        $comment = $MS_variable::variable{$variable}{comment};
    }

    $query = qq|
        REPLACE INTO config
            (variable, value, scope, scope_data, comment, changed)
        VALUES
            (?,?,?,?,?,NOW())
    |;

    $sth = $dbh->prepare($query) or do {
        print STDERR "Failed to prepare INSERT query: $dbh->errstr\n";
        exit 1;
    };

    my $ins_scope = $scope || 'global';
    my $ins_scope_data = $scope_data || '';

    $sth->execute($variable,$updated,$ins_scope,$ins_scope_data,$comment)
      or do {
        print STDERR "Failed to execute INSERT query: $dbh->errstr\n";
        exit 1;
    }
}


my $sth = $dbh->prepare($query);
$sth->execute($value, $variable);
my $rows = $sth->rows;
if ($rows) {
    print "Rows affected: $rows\n";
}
$sth->finish;

$dbh->disconnect;
    
