#!/usr/bin/perl

use Modern::Perl;
use File::Copy;
use Getopt::Long;
my %args;
my $result = GetOptions(\%args, 'verbosity+');

unless (@ARGV == 1) {
    say "usage: $0 ssh-config-file";
    exit 1;
}
my $filename  = shift;
my $newfilename = $filename . 'new';

open (OLD, $filename) or die;
open (NEW, '>', $newfilename) or die;

my $host;

foreach (<OLD>) {
    my $newline = $_;
    if (/^Host\s+(\S+)/) { # this is the start of a new host paragraph
        $host = $1;
    }
    elsif (/\s+HostName\s+(\d{3}.\d{3}.\d.\d)/) { # this
        my $oldip = $1;
        my $newip = qx(host $host);
        $newip =~ s/.*(\d{3}.\d{3}.\d.\d).*/$1/s;
        $newline =~ s/$oldip/$newip/ if ($newip =~ /^\d{3}.\d{3}.\d.\d$/);
    }
    print NEW $newline;
    print $newline if $args{verbosity};
}

close(OLD);
close(NEW);

copy($filename, ($filename . '.old'));
move($newfilename, $filename);