#!/usr/bin/env bash

T=90
OUTFILE="pg_stat_activity.log"

pgbench -i -s10
pgbench -n -c 200 -j 1 -T "$T" -P 1 -M prepared &
PGBENCH_PID=$!

# Loop every second, dump pg_stat_activity
END=$((SECONDS + T))
> "$OUTFILE"  # clear file

while (( SECONDS < END )); do
	psql -d "$PGDATABASE" -X -q -c "SELECT 'STATS', state, coalesce(wait_event, 'CPU') wait_event, backend_type FROM pg_stat_activity;" >> "$OUTFILE"
    sleep 1
done

wait "$PGBENCH_PID"

echo -e "\n\n# of samplase of state = active, wait_event = ClientRead and backend_type = client backend"
grep -c "active.*ClientRead.*client backend" pg_stat_activity.log
echo -e "\n\n# of sampled of state = active + wait_event"
cat pg_stat_activity.log | grep STATS | grep active | awk '{print $3}' FS="|" | sort | uniq -c |sort -nr