DIRECTORY=`pwd`
LOGS=$DIRECTORY/.logs
DATADIR=/mnt/ssd-s3700/gindata
PATH=/home/postgres/pg-gin/bin:/home/postgres/archie/bin:$PATH

ulimit -c unlimited

p=$1
n=$2

killall -9 postgres > /dev/null 2>&1

rm -Rf $DATADIR/data > /dev/null 2>&1
rm -Rf /home/postgres/pg-gin > /dev/null 2>&1

cd /home/postgres/postgres

git checkout $p > $LOGS/git.$p.log 2>&1
git clean -f -d >> $LOGS/git.$p.log 2>&1

./configure --prefix=/home/postgres/pg-gin --enable-debug --enable-cassert > $LOGS/config.$p.log 2>&1
make -s clean
make -s -j8 install > $LOGS/install.$p.log 2>&1

cd contrib
make -s clean
make -s -j8 install >> $LOGS/install.$p.log 2>&1

cd $DIRECTORY

pg_ctl -D $DATADIR/data -l $LOGS/pg.$p.default.log init > $LOGS/init.$p.default.log 2>&1

cp postgresql.conf $DATADIR/data/postgresql.conf

pg_ctl -D $DATADIR/data -l $LOGS/pg.$p.tuned.log -w start >> $LOGS/start.$p.tuned.log 2>&1

for i in `seq 1 $n`; do

    createdb archie > /dev/null 2>&1

    psql archie < /home/postgres/archie/sql/create.sql >> $LOGS/create.$p.$i.tuned.log 2>&1
    load.py --workers 8 --db archie */* >> $LOGS/load.$p.$i.tuned.log 2>&1

    psql archie -c "COPY messages TO '/mnt/sas-raid10/gindata/messages.$p'" >> $LOGS/copy.$p.$i.tuned.log 2>&1

    dropdb archie > /dev/null 2>&1

done;
