#!/bin/sh
set -eu


usage() {
	cat <<-'EOF'
		Usage:
		  free-port
		  free-port -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -h, --help    show this message


		Returns a free TCP port.


		Examples:

		  Get a port for a command:

		    $ cmd -p `free-port`
	EOF
}


for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

while getopts 'h' flag; do
	case "$flag" in
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))


MIN_PORT=1024
MAX_PORT=65536

gen_port() {
	shuf -n1 -i "${MIN_PORT}-${MAX_PORT}"
}

while true; do
	PORT="$(gen_port)"
	if ! lsof -s TCP:LISTEN -i ":$PORT" >/dev/null; then
		break
	fi
done

printf '%s\n' "$PORT"
