#!/bin/sh -e

usage() {
  cat <<EOF
$(basename "$0")
  a simple monitor and manage processes by ports

commands:
  [l]s          - List all open ports and the processes running in them.
  [s]how [port] - Shows which process is running on a given port.
  [p]id  [port] - Same as show, but prints only the PID.
  kill   [port] - Kill the process is running in the given port with kill.

flags:
  -h, --help    - Display this message.
EOF
  exit 0
}

os=$(uname -s | tr '[:upper:]' '[:lower:]' | cut -d '/' -f 2 | cut -d '_' -f 1)

pp_ports() {
  if [ "${os}" = "linux" ]; then
    lsofcmd="sudo lsof"
  else
    lsofcmd="lsof"
  fi
  # shellcheck disable=SC2034,SC2312
  ${lsofcmd} -iTCP -n -P \
    | awk 'NR>1 { print $9, $1, $2 }' \
    | sed 's/.*://' \
    | while read -r port process pid; do
      echo "Port ${port}: $(ps -p "${pid}" -o command= | sed 's/^-//') (PID: ${pid})"
    done \
    | sort -n
}

case "$1" in
  l | ls)
    if [ "${os}" = "linux" ]; then
      sudo lsof -i -n -P
    else
      lsof -i -n -P
    fi
    ;;
  s | show)
    if [ "${os}" = "linux" ]; then
      sudo lsof -i :"$2" | tail -n 1
    else
      lsof -i :"$2" | tail -n 1
    fi
    ;;
  p | pid)
    if [ "${os}" = "linux" ]; then
      sudo lsof -i :"$2" | tail -n 1 | awk '{ print $2; }'
    else
      lsof -i :"$2" | tail -n 1 | awk '{ print $2; }'
    fi
    ;;
  kill)
    if [ "${os}" = "linux" ]; then
      # shellcheck disable=SC2312
      sudo kill "$(sudo lsof -i :"$2" | tail -n 1 | awk '{ print $2; }')"
    else
      # shellcheck disable=SC2312
      kill "$(lsof -i :"$2" | tail -n 1 | awk '{ print $2; }')"
    fi
    ;;
  -h | --help)
    usage
    ;;
  *)
    pp_ports
    ;;
esac
