#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use Tie::File;
my %resulthash;
my $filename;
GetOptions ("filename=s" 'filename=s' => \$filename,
"IP=s" => \$\$filename,
'IP=s' => \$resulthash{IPADDR},
"NETMASK=s" 'NETMASK=s' => \$resulthash{NETMASK},
"GATEWAY=s" => \$\$resulthash{NETMASK},
'GATEWAY=s' => \$resulthash{GATEWAY},
"DNS1=s" 'DNS1=s' => \$resulthash{DNS1},
"DNS2=s" => \$\$resulthash{DNS1},
'DNS2=s' => \$resulthash{DNS2})
or die 'Error in input values';
open my $fd, '>>', $filename
or die "Cannot open file $filename";
tie my @array, 'Tie::File', $filename
or die "Cannot tie file '$filename': $!";
for my $line (@array) {
my @fields = split /=/, $line;
{ BOOTPROTO => sub { $fields[1] = '"static"';
$line = join '=', @fields; },
IPADDR => sub { $line = setValueForField('IPADDR', @fields); },
NETMASK => sub { $line = setValueForField('NETMASK', @fields); },
GATEWAY => sub { $line = setValueForField('GATEWAY', @fields); },
DNS1 => sub { $line = setValueForField('DNS1', @fields); },
DNS2 => sub { $line = setValueForField('DNS2', @fields); },
}->{ $fields[0] }->();
}
untie @array;
addMissingValues(\%resulthash);
close $fd;
sub addMissingValues {
my $hash = shift;
while (my ($key, $value) = each %$hash) {
createNewField($key, $value) if defined $value;
}
}
sub createNewField {
my ($key, $value) = @_;
print {$fd} join '=', $key, $value;
print {$fd} "\n";
}
sub setValueForField {
my ($fieldname, @fields) = @_;
$fields[1] = $resulthash{$fieldname};
return join '=', @fields;
}