#!/bin/sh

# trap ctrl-c and call ctrl_c()
trap ctrl_c INT

ctrl_c() {
  echo
  echo 'Caught Ctrl-C. Exiting...'
  exit 1
}

exclusions='\.(([2-9]{1}[5-9][6-9])|([3-9]{1}[0-9][0-9])|([2-9]{1}[6-9][0-9]))|(([2-9]{1}[5-9][6-9])|([3-9]{1}[0-9][0-9])|([2-9]{1}[6-9][0-9]))\.'
ipv4regex='(([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\.){3}([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))'
ipv4portregex='(([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\.){3}([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\:[1-9]{1}[0-9]{,4}'
portexclusions='(:[6-9][6-9][0-9][0-9][0-9])|(:6553[6-9])|(:655[4-9][0-9])|(:65[6-9][0-9][0-9])'
ipv4cidrregex='(([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\.){3}([1-9]?[0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))/[0-9]{1,2}'

grepfile() { grep -vE "$ipv4cidrregex" "${@}" | grep -oE "$ipv4portregex" "${@}" | grep -vE "$exclusions" | grep -vE "$portexclusions"; }
grepit() { grep -vE "$ipv4cidrregex" | grep -oE "$ipv4portregex" | grep -vE "$exclusions" | grep -vE "$portexclusions"; }

# if arguments are passed:
if [ ! -z $1 ]; then
  for i in ${@}; do
    # if $i is a file:
    if [ -f "$i" ]; then
      grepfile "$i"
    else
      # if argument is input from stdin:
      echo "$i" | grepit
    fi
  done
else
  grepit
fi
