#!/bin/bash
## Set your PGHOME here
#PGHOME="/usr/local/debug/pgsql/"

## Set yout PGDATA
DBCLUSTER="/test/cluster"

cd /home/postgres

${PGHOME}/bin/pg_ctl -D  ${DBCLUSTER} stop
rm -rf ${DBCLUSTER}
${PGHOME}/bin/initdb -D ${DBCLUSTER} --no-locale -E UTF8 -k

## Configuration
echo "logging_collector = on"  >> ${DBCLUSTER}/postgresql.conf
echo "autovacuum_freeze_max_age = 200000" >> ${DBCLUSTER}/postgresql.conf
echo "autovacuum_naptime = 5s"  >> ${DBCLUSTER}/postgresql.conf
echo "autovacuum_max_workers = 5" >> ${DBCLUSTER}/postgresql.conf
echo "vacuum_freeze_min_age = 0"  >> ${DBCLUSTER}/postgresql.conf
echo "max_locks_per_transaction = 5000" >> ${DBCLUSTER}/postgresql.conf

${PGHOME}/bin/pg_ctl -D ${DBCLUSTER} start

## Create tables (20000)
${PGHOME}/bin/psql << "EOF"
DO $$ DECLARE v1 int;
BEGIN
  FOR v1 IN 1..20000 LOOP
    EXECUTE 'CREATE TABLE tbl_' || v1::text || ' (col1 int)';
  END LOOP;
END$$;
EOF

## Select each tables
${PGHOME}/bin/psql << "EOF"
DO $$ DECLARE v1 int;
BEGIN
  FOR v1 IN 1..20000 LOOP
    EXECUTE 'SELECT * FROM  tbl_' || v1::text || ' LIMIT 1';
  END LOOP;
END$$;
EOF

${PGHOME}/bin/pg_ctl -D ${DBCLUSTER} stop
${PGHOME}/bin/pg_ctl -D ${DBCLUSTER} start

## Consume XIDs (over autovacuum_freeze_max_age) for issuing prevent wrap-round vacuums
${PGHOME}/bin/psql << "EOF"
CREATE OR REPLACE PROCEDURE waste_xid(cnt int) AS $$ DECLARE i int;
BEGIN
  FOR i in 1..cnt LOOP
    EXECUTE 'SELECT txid_current()';
    COMMIT;
  END LOOP;
END;
$$ LANGUAGE plpgsql;
EOF

${PGHOME}/bin/psql -c "CALL waste_xid(200000);"
