#!/bin/sh
#
# Find amount of data going through a Squid caching proxy that is
# actually being served from the proxy rather from the web. Expects a
# standard formatted Squid log.

if [ -z "$1" ]; then
  echo "Usage: $0 <log-path>"
  exit 1
fi

echo "Reading logs..."
TCP_HITS=$(zcat -f $@ | egrep -e \
"TCP_(((MEM|IMS_)?HIT)|REFRESH_UNMODIFIED)"| awk \
'BEGIN{s=0;l=0} ; {l=l+1; s = s+ $5}; END{print l,s}')
TCP_HITS_COUNT=$(echo $TCP_HITS | cut -f 1 -d " ")
TCP_HITS_BYTES=$(echo $TCP_HITS | cut -f 2 -d " ")

TCP_MISS=$(zcat -f $@ | egrep -e "TCP_(SWAPFAIL_)?MISS" | egrep -v \
"TCP_MISS_(ABORTED|TIMEOUT)" | awk 'BEGIN{s=0;l=0} ; {l=l+1; s = \
s+ $5}; END{print l,s}')
TCP_MISS_COUNT=$(echo $TCP_MISS | cut -f 1 -d " ")
TCP_MISS_BYTES=$(echo $TCP_MISS | cut -f 2 -d " ")

TCP_REFRESH=$(zcat -f $@ | egrep -e "TCP_REFRESH_MODIFIED" | awk \
'BEGIN{s=0;l=0} ; {l=l+1; s = s+ $5}; END{print l,s}')
TCP_REFRESH_COUNT=$(echo $TCP_REFRESH | cut -f 1 -d " ")
TCP_REFRESH_BYTES=$(echo $TCP_REFRESH | cut -f 2 -d " ")

TCP_TUNNEL=$(zcat -f $@ | egrep -e "TCP_TUNNEL" | awk \
'BEGIN{s=0;l=0} ; {l=l+1; s = s+ $5}; END{print l,s}')
TCP_TUNNEL_COUNT=$(echo $TCP_TUNNEL | cut -f 1 -d " ")
TCP_TUNNEL_BYTES=$(echo $TCP_TUNNEL | cut -f 2 -d " ")

TCP_TOTAL_COUNT=$(expr $TCP_HITS_COUNT + $TCP_MISS_COUNT + \
$TCP_REFRESH_COUNT + $TCP_TUNNEL_COUNT)
TCP_TOTAL_BYTES=$(expr $TCP_HITS_BYTES + $TCP_MISS_BYTES + \
$TCP_REFRESH_BYTES + $TCP_TUNNEL_BYTES)

PERCENT_HITS_CONN=$(printf "% 5.1f" `echo "scale=2; 100 * \
$TCP_HITS_COUNT / $TCP_TOTAL_COUNT" | bc` )
PERCENT_MISS_CONN=$(printf "% 5.1f" `echo "scale=2; 100 * \
$TCP_MISS_COUNT / $TCP_TOTAL_COUNT" | bc` )
PERCENT_UNFRESH_CONN=$(printf "% 5.1f" `echo "scale=2; 100 * \
$TCP_REFRESH_COUNT / $TCP_TOTAL_COUNT" | bc` )

PERCENT_HITS_BYTES=$(printf "% 5.1f" `echo "scale=2; 100 * \
$TCP_HITS_BYTES / $TCP_TOTAL_BYTES" | bc` )
PERCENT_MISS_BYTES=$(printf "% 5.1f" `echo "scale=2; 100 * \
$TCP_MISS_BYTES / $TCP_TOTAL_BYTES" | bc` )
PERCENT_UNFRESH_BYTES=$(printf "% 5.1f" `echo "scale=2; 100 * \
$TCP_REFRESH_BYTES / $TCP_TOTAL_BYTES" | bc` )

echo "${PERCENT_HITS_CONN}% of connections were served from \
the cache."
echo -e "${PERCENT_HITS_BYTES}% of data (${TCP_HITS_BYTES} \
bytes).\n"

echo "${PERCENT_UNFRESH_CONN}% of connections needed to be \
refreshed in the cache before serving."
echo -e "${PERCENT_UNFRESH_BYTES}% of data \
(${TCP_REFRESH_BYTES} bytes).\n"

echo "${PERCENT_MISS_CONN}% of connections were served from \
the Web."
echo -e "${PERCENT_MISS_BYTES}% of data (${TCP_MISS_BYTES} \
bytes).\n"

exit 0