#!/bin/bash

if [ ! -d contrib ]; then
  echo "script should be run from the postgres source tree root"
  exit 1
fi

mkdir -p build
cd build
export PATH=`pwd`/install/usr/local/pgsql/bin/:$PATH
export LD_LIBRARY_PATH=`pwd`/install/usr/local/pgsql/lib
pg_ctl -D data/ -l logfile stop

if [ -z $1 ]; then
  LOW=950
  rm -rf *
  unset CFLAGS
  export CFLAGS=-Wno-error=implicit-function-declaration
  ../configure --without-icu
  make -j12
  make install -j12 DESTDIR=`pwd`/install
else
  LOW=$1
fi

rm -rf data
rm -f logfile
initdb -D data/
sed -i 's/^#port.=.5432/port = 65432/' data/postgresql.conf
sed -i 's/^#autovacuum_naptime.=.1min/autovacuum_naptime = 1s/' data/postgresql.conf
sed -i 's/^#max_locks_per_transaction.=..../max_locks_per_transaction = 256/' data/postgresql.conf
pg_ctl -D data/ -l logfile start
export PGDATABASE=postgres
export PGPORT=65432
export PGHOST=/tmp
psql -c "DO \$\$ DECLARE i INT; BEGIN FOR i IN SELECT generate_series(1, 7500) LOOP EXECUTE format('CREATE TABLE IF NOT EXISTS table_%s (id INT)', i); END LOOP; END \$\$;"
psql -c "BEGIN; DROP TABLE table_7500; SELECT pg_sleep(1000);" &
sleep 3

# drop tables from $LOW to last-but-one
# worst case for proposed scanned tuple percentage threshold: 990
# worst case for proposed density threshold: 6120
# worst case for final reltuples: 946
# use provided command-line parameter
psql -c "DO \$\$ DECLARE i INT; BEGIN FOR i IN SELECT generate_series($LOW,7499) LOOP EXECUTE format('DROP TABLE IF EXISTS table_%s', i); END LOOP; END \$\$;"

psql -c "SELECT ctid, relname FROM pg_class ORDER BY ctid DESC LIMIT 2;"
for i in $(seq 1 10); do
  psql -c "SELECT c.relname, n_live_tup, n_dead_tup, n_mod_since_analyze, autovacuum_count, autoanalyze_count, relpages, reltuples FROM pg_stat_sys_tables s, pg_class c WHERE s.relid = c.oid AND c.relname = 'pg_class'"
  sleep 1
done

pkill -P $$
