#!/usr/bin/perl

if (@ARGV==0) {
	print "Usage: ipf [-sl] <IP>\n";
	print "   or: cat <file> | ipf -\n";
	print "\n\nConvert ip addresses between form 137.99.201.5 and 137.099.201.005\n\n";
   print " -s  Force to short format 137.099.004.012   -> 137.99.44.12\n";
   print " -l  Force to long  format 137.99.4.12       -> 137.099.004.012\n";
   print "  otherwise autoconvert\n";
	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;
}

#  check for stdin
if ($ARGV[0] eq '-') {
	while (<STDIN>) {
		chomp;
		print &ipformat($_),"\n";
		}
	exit(0);
	}

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 "-";
			}
	}
}
