#!/bin/bash
# Skrypt weberrors wyszukujący w pliku error_log serwera Apache
# najważniejsze błędy i wyświetlający nierozpoznane wpisy.

temp="/tmp/$(basename $0).$$"

# Poniższe trzy wiersze zmień odpowiednio do konfiguracji
# swojego systemu.

htdocs="/usr/local/etc/httpd/htdocs/"
myhome="/usr/home/taylor/"
cgibin="/usr/local/etc/httpd/cgi-bin/"

sedstr="s/^/ /g;s|$htdocs|[htdocs] |;s|$myhome|[homedir] "
sedstr=$sedstr"|;s|$cgibin|[cgi-bin] |"

screen="(File does not exist|Invalid error redirect|premature EOF"
screen=$screen"|Premature end of script|script not found)"

length=5                # Liczba wyświetlanych błędów w każdej kategorii.

checkfor() 
{
  grep "${2}:" "$1" | awk '{print $NF}' |\
    sort | uniq -c | sort -rn | head -$length | sed "$sedstr" > $temp

  if [ $(wc -l < $temp) -gt 0 ] ; then
    echo ""
    echo "Błędy '$2':"
    cat $temp
  fi
}

trap "`which rm` -f $temp" 0

if [ "$1" = "-l" ] ; then
  length=$2; shift 2
fi

if [ $# -ne 1 -o ! -r "$1" ] ; then
  echo "Użycie: $(basename $0) [-l długość] error_log" >&2
  exit 1
fi

echo Plik $1 składa się z $(wc -l < "$1") wierszy.

start="$(grep -E '\[.*:.*:.*\]' "$1" | head -1 \
  | awk '{print substr($1,2,3)" "$2" "$3" "$4" "substr($5,1,4) }')"
start=$(date -d "$start" +"%Y-%m-%d %H:%M:%S")
end="$(grep -E '\[.*:.*:.*\]' "$1" | tail -1 \
  | awk '{print substr($1,2,3)" "$2" "$3" "$4" "substr($5,1,4) }')"
end=$(date -d "$end" +"%Y-%m-%d %H:%M:%S")

echo -n "Dane za okres od $start do $end."

echo ""

### Wyszukanie najczęściej spotykanych komunikatów o błędach:

checkfor "$1" "File does not exist"
checkfor "$1" "Invalid error redirection directive"
checkfor "$1" "premature EOF"
checkfor "$1" "script not found or unable to stat" 
checkfor "$1" "Premature end of script headers" 

grep -vE "$screen" "$1" | grep "\[error\]" | grep "\[client " | \
  sed 's/\[error\]/\`/' | cut -d\`  -f2 | cut -d\  -f4- | \
  sort | uniq -c | sort -rn | sed 's/^/  /' | head -$length > $temp

if [ $(wc -l < $temp) -gt 0 ] ; then
  echo ""
  echo "Inne komunikaty o błędach:"
  cat $temp
fi

echo ""
echo "Pozostałe komunikaty:"

grep -vE "$screen" "$1" | grep -v "\[error\]" | \
  sort | uniq -c | sort -rn | \
  sed 's/^/  /' | head -$length

exit 0
