#!/usr/bin/perl
#
# Module: vyatta_update_sysctl.pl
# 
# **** License ****
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
# 
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# A copy of the GNU General Public License is available as
# `/usr/share/common-licenses/GPL' in the Debian GNU/Linux distribution
# or on the World Wide Web at `http://www.gnu.org/copyleft/gpl.html'.
# You can also obtain it by writing to the Free Software Foundation,
# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
# MA 02110-1301, USA.
# 
# This code was originally developed by Vyatta, Inc.
# Portions created by Vyatta are Copyright (C) 2007 Vyatta, Inc.
# All Rights Reserved.
# 
# Author: Jason Hendry
# Date: October 2014
# Description: Script to manage sysctl values
# 
# **** End License ****
#

use lib "/opt/vyatta/share/perl5/";
use Vyatta::Config;
use Vyatta::File qw(touch);

use strict;
use warnings;

my $sysctl_option_name = '';
my $sysctl_option_values = '';
my $sysctl_option_values_count = 0;
my $sysctl_vyos_path = '/sbin/sysctl';

sub usage {
    print <<EOF;
Usage: $0 --option=<sysctl_option> <values>
EOF
    exit 1;
}

sub get_sysctl_values {
    my ($option, $sysctl_path) = @_;
    my @values = ();

    open(my $sysctl_capture, '-|', "$sysctl_path $option 2>&1") or die "sysctl failed: $!\n";
    
    while (<$sysctl_capture>) {
        chomp;
        @values = split(' ', $_);
    }
    
    close $sysctl_capture;
    
    return (@values);
}

sub set_sysctl_values {
    my ($option, $val_count, $new_values, $sysctl_path) = @_;
    my $set_new_values = undef;
    my $sysctl_cmd = '';
    my @original_values = ();
    
    @original_values = get_sysctl_values($option,$sysctl_path);
    
    for(my $x = 0; $x < $val_count; $x = $x + 1) {
        if($ARGV[$x+2] ne $original_values[$x+2]) {
            $set_new_values = 1;
            last;
        }
    }
    
    if ($set_new_values) {
        if($val_count > 1) {
            $sysctl_cmd = "$sysctl_path -w $option=\"$new_values\" 2>&1> /dev/null";
        } else {
            $sysctl_cmd = "$sysctl_path -w $option=$new_values 2>&1> /dev/null";
        }
        
        system($sysctl_cmd);
        
        if ($? >> 8) {
            die "exec of $sysctl_path failed: '$sysctl_cmd'";
        } 
    }
}

if ($#ARGV < 2 ) {
	usage();
} else {
    $sysctl_option_name = $ARGV[1];
    $sysctl_option_values_count = $#ARGV-1;
    $sysctl_option_values = "@ARGV[2 .. $#ARGV]";
    
    set_sysctl_values($sysctl_option_name, $sysctl_option_values_count, $sysctl_option_values, $sysctl_vyos_path);
    
    exit 0;
}
