#!/bin/bash

. paths.sh
PGDATA=pgdata_imdb
pg_ctl -D $PGDATA stop
pkill -U $PGUSER -9 postgres || true
rm -rf logfile.log

sleep 1
pg_ctl -w -D $PGDATA -l logfile.log start

filenum=0

echo "|| file | TimeAQO | USE AQO | NJOINS | HASH || TimeNAQO | USE ||"
for file in ../imdb/queries/*.sql
do
  # Get filename
  short_file=$(basename "$file")

  # Prepare query before execution
  echo "SET aqo.mode = 'frozen';" > test.sql
  echo -n "EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS, FORMAT JSON) " >> test.sql
#  echo -n "EXPLAIN ANALYZE verbose " >> test.sql
  cat $file >> test.sql

  result=$(psql -qAt -f "test.sql")
  time=$(echo "$result" | grep "Execution Time" | awk '{print $3}' | sed 's/,//')
  use_aqo=$(echo "$result" | grep "aqo" | awk '{print $3}' | sed 's/,//')
  joins=$(echo "$result" | grep "JOINS" | awk '{print $2}' | sed 's/,//')
  hash=$(echo "$result" | grep "Query hash" | awk '{print $3}' | sed 's/,//')

  echo "$result" > $i"_"$short_file".json"
  echo -n "|| $short_file | $time | $use_aqo | $joins | $hash |"

  # Prepare query before execution
  echo "SET aqo.mode = 'disabled';" > test.sql
  echo -n "EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS, FORMAT JSON) " >> test.sql
#  echo -n "EXPLAIN ANALYZE verbose " >> test.sql
  cat $file >> test.sql

  naqo_result=$(psql -qAt -f "test.sql")
  echo "$naqo_result" > $i"_n"$short_file".json"
  time=$(echo "$naqo_result" | grep "Execution Time" | awk '{print $3}')
  use_aqo=$(echo "$naqo_result" | grep "aqo")

  echo "| $time | $use_aqo ||"
  filenum=$((filenum+1))
done

pg_ctl -D $PGDATA stop
rm test.sql