#!/usr/bin/perl

&Usage if @ARGV==0;

sub Usage {
print <<'EOM';

   Usage: ipf [-sl] <ip>
      or: cat <file> | ipf -
   
   Convert ip addresses between form 137.99.201.5 and 137.099.201.005

    -s  Force to short format 137.099.004.012   -> 137.99.44.12
    -l  Force to long  format 137.99.4.12       -> 137.099.004.012

    otherwise autoconvert

EOM
exit;
}

#  check for options
if ($ARGV[0] eq '-s') {
  $format=1;
   shift @ARGV;
} elsif ($ARGV[0] eq '-l') {
  $format=2;
   shift @ARGV;
} else {
  $format=0;
}

#  Read data from standard int
if ($ARGV[0] eq '-') {
   while ($in=<STDIN>) {
      chomp $in;
      #  Get all ip addresses on this line
      @ip = $in=~/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/g;
      #  Split line on ip addresses to get inbetween stuff
      @bg = split /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/, $in;
      #  Reformat ip addresses
      for (@ip) { $_ = &ipformat($_); }
      #  Re-assemble line
      print $bg[0];
      for ($i=0;$i<@ip;$i++) { print $ip[$i], $bg[$i+1]; }
      print "\n";
   }
   exit(0);
}

#  Read data from command line
print &ipformat($ARGV[0]), "\n";

exit;

sub ipformat {

   my ($ip) = @_;

   #  Switch existing format (autoformat)
   if ($format==0) {

        # already in long format, force short
        if ($ip=~/(\d{3})\.(\d{3})\.(\d{3})\.(\d{3})/) {
           sprintf "%d.%d.%d.%d", $1, $2, $3, $4;

        #  already in short format, force long
        } elsif ($ip=~/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/) {
           sprintf "%03d.%03d.%03d.%03d", $1, $2, $3, $4;

        #  not ip address
        } else { 
            sprintf "-";
        }

   #  Force format
   } else {

      #  Test if ip address
      if ($ip=~/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/) {

         #  Print short format
         if ($format==1) {
            sprintf "%d.%d.%d.%d", $1, $2, $3, $4;
   
         #  Print long format
         } else {
            sprintf "%03d.%03d.%03d.%03d", $1, $2, $3, $4;
         }

      #  not ip address
      } else { 
         sprintf "-";
      }
   }
}
