#!/bin/bash
progress() {
    LINE="$( printf "$@" )"
    echo "$( date +'%Y-%m-%d %H:%M:%S') $LINE"
    psql -d template1 -U postgres -qAtX -c "SELECT ':PROGRESS: $LINE'" &>/dev/null
}

cat run.test.data | while read LINE
do
    table="$( echo "$LINE" | awk '{print $1}' )"
    words="$( echo "$LINE" | sed 's/^[^[:space:]]*[[:space:]]*//' )"
    progress 'Starting test of table %s' "$table"
    for index_type in gist gin
    do
        progress '  Index creation for %s on %s' "$index_type" "$table"
        for i in $( seq 1 10 )
        do
            psql -c "drop index if exists test_index" &>/dev/null
            psql -c "create index test_index on $table using $index_type ( to_tsvector('english'::regconfig, body) )" &>/dev/null
        done
        psql -c "analyze $table" &>/dev/null
        for word in $words
        do
            progress '    Searches (count(*)) for %s using %s on %s' "$word" "$index_type" "$table"
            for i in $( seq 1 10 )
            do
                psql -c "select count(*) from $table where to_tsvector('english'::regconfig, body) @@ to_tsquery('english', '$word')" &>/dev/null
            done
            progress '    Searches (by created) for %s using %s on %s' "$word" "$index_type" "$table"
            for i in $( seq 1 10 )
            do
                psql -c "select id from $table where to_tsvector('english'::regconfig, body) @@ to_tsquery('english', '$word') order by created asc limit 50" &>/dev/null
            done
            progress '    Searches (by title) for %s using %s on %s' "$word" "$index_type" "$table"
            for i in $( seq 1 10 )
            do
                psql -c "select id from $table where to_tsvector('english'::regconfig, body) @@ to_tsquery('english', '$word') order by title asc limit 50" &>/dev/null
            done
        done
    done
done
