#!/usr/pkg/bin/bash
#
# A very lame script for making explain output easier to sort through via a web browser.
# Requires the explain.conf file in the same directory

# Change these to what you want.

database="planning"
user="iharding"
filename=/tmp/explain.html

# Other variables...

oldifs=${IFS}
IFS="
"
numtests=`cat explain.conf | wc -l`
query=$1

# Read the config file.  First column is the string to grep, the second is the
# font format you want.

c=0
while read row
do
        c=`expr $c + 1`
        testval[$c]=`echo "$row" | cut -f1`
        format[$c]=`echo "$row" | cut -f2`
        counter[$c]=0
done < explain.conf

# Run the query and put the results in tmp.
# Cant assign directly to the variable since the good stuff is in stderr.

echo "explain $1" | psql -d $database -U $user &> /tmp/explain
data=`cat /tmp/explain`

# Loop through the data and find matches.  Update counts.

set $data
for field
do
    i=0
    found=0
    while [ $i -lt $numtests ]
    do
        i=`expr $i + 1`
        if echo $field | grep "${testval[$i]}" > /dev/null
        then
            html="${html}<font ${format[$i]}>`echo "$field" | sed 's/  /\&nbsp;/g'` </font><br>"
            counter[$i]=`expr ${counter[$i]} + 1`
            found=1
            break
        fi
    done
    if [ $found == 0 ]
    then
        html="${html} `echo "$field" | sed 's/  /\&nbsp;/g'` <br>"
    fi
done

# Start output

echo "<html><head><title>Explain Results</title></head><body>" > $filename
echo "<h1>Explain for  $query </h1>" >> $filename
i=0

# Put out the counts.

while [ $i -lt $numtests ]
do
    i=`expr $i + 1`
    echo "<font ${format[$i]}>${testval[$i]}: ${counter[$i]}</font><br>" >> $filename
done

echo "<p>$html</body></html>" >> $filename

# Put things back how they were

IFS=${oldifs}
