#!/bin/bash

aports=`lsof -n -P -c apache2 |grep TCP | grep LISTEN |awk '{ print $9}' |sort |uniq |sed 's/\*://'`

for aport in $aports; do

	colnames=`curl -s http://localhost:$aport/server-status | sed -n '/<table/,/<table>/p' |\
	perl -0777 -pe 's|<tr>(.*?)</tr>|"<tr>" . ($1 =~ s/\n//gr) . "</tr>"|gse' |\
	grep "<tr><th>" | sed 's/<[^>]*>/ /g'`

	if [ -n "$colnames" ]; then

		i=1

		cn_m=''
		cn_pid=''
		cn_vh=''
		cn_url=''

		for colname in $colnames; do

			case $colname in
				M)
					cn_m=$i
					;;
				PID)
					cn_pid=$i
					;;
				VHost)
					cn_vh=$i
					;;
				Request)
					cn_url=$((i + 1))
					;;
			esac

			((i++))

		done

		if [ -n "$cn_pid" ]; then

			curl -s http://localhost:$aport/server-status | sed -n '/<table/,/<table>/p' |\
			perl -0777 -pe 's|<tr>(.*?)</tr>|"<tr>" . ($1 =~ s/\n//gr) . "</tr>"|gse' |\
#			grep "<tr><td>" | sed 's/<[^>]*>/ /g' | awk '{print $'$cn_m' " " $'$cn_pid' " " $'$cn_vh' $'$cn_url'}' | grep '^\(W\)' |grep -v '/server-status' | while read -r _ pid url
			grep "<tr><td>" | sed 's/<[^>]*>/ /g' | awk '{print $'$cn_m' " " $'$cn_pid' " " $'$cn_vh' $'$cn_url'}' | grep '^\(W\)' | while read -r _ pid url
			do
				echo
				echo "*** $aport $url ***"
				echo
				lsof -n -P -p $pid | grep -v " \(mem\|DEL\) "
			done
		fi
	fi

done
