#!/usr/bin/env bash

PORT80=80
PID80=""

if command -v lsof >/dev/null 2>&1; then
    PID80=$(lsof -nP -t -iTCP:"${PORT80}" -sTCP:LISTEN 2>/dev/null | head -n1)
elif command -v ss >/dev/null 2>&1; then
    PID80=$(ss -H -ltnp "sport = :${PORT80}" 2>/dev/null \
        | sed -n 's/.*pid=\([0-9][0-9]*\).*/\1/p' \
        | head -n1)
elif command -v fuser >/dev/null 2>&1; then
    PID80=$(fuser -n tcp "${PORT80}" 2>/dev/null | tr ' ' '\n' | grep -E '^[0-9]+$' | head -n1)
fi

if [[ -n "${PID80}" && -e "/proc/${PID80}/exe" ]]; then
    name=$(basename "$(readlink -f "/proc/${PID80}/exe" 2>/dev/null)")
    if [[ -n "$name" ]]; then
        echo "$name"
        exit 0
    else
        # Something is listening, but we couldn't identify it.
        exit 1
    fi
fi

exit 0
