PGHOME=/tmp/pgsql
PGPORT=15433

function build_check {
    echo "make PGSQL_INCLUDE_DIR=..."
    make PGSQL_INCLUDE_DIR=../../src/include clean
    make PGSQL_INCLUDE_DIR=../../src/include all
    make PGSQL_INCLUDE_DIR=../../src/include install
    make PGSQL_INCLUDE_DIR=../../src/include clean
    
    echo "make -f Makefile.contrib..."
    make -f Makefile.contrib clean
    make -f Makefile.contrib all
    make -f Makefile.contrib install
    make -f Makefile.contrib clean
    
    echo "make -f Makefile.contrib USE_PGXS=1..."
    PATH=${PGHOME}/bin:$PATH
    make -f Makefile.contrib USE_PGXS=1 clean
    make -f Makefile.contrib USE_PGXS=1 all
    make -f Makefile.contrib USE_PGXS=1 install
    make -f Makefile.contrib USE_PGXS=1 clean
}

function do_builddb {
    INITDB_OPTS=$1
    killall -9 postmaster postgres
    rm -rf ${PGHOME}/data
    
    initdb ${INITDB_OPTS} --no-locale -D ${PGHOME}/data
    pg_ctl -w -D ${PGHOME}/data start -o "-p ${PGPORT}"
    createdb -p ${PGPORT} testdb
    pgbench -p ${PGPORT} -i testdb
    
    psql -A -t -p ${PGPORT} testdb<<EOF > file
select '${PGHOME}/data/' || pg_relation_filepath(oid) from pg_class where relname like 'pgbench%';
EOF
}

function builddb_checksum_enabled {
    do_builddb "-k"
}

function builddb_checksum_disabled {
    do_builddb ""
}

function test_not_verify_checksum {
    LOG=$1
    sed 's/^/pg_filedump /' < file > _test.sh
    sh _test.sh > $LOG
}

function test_verify_checksum {
    LOG=$1
    sed 's/^/pg_filedump -k /' < file > _test.sh
    sh _test.sh > $LOG
}

build_check

builddb_checksum_enabled
test_not_verify_checksum "test_enabled_not_verify.log"
test_verify_checksum "test_enabled_verify.log"

builddb_checksum_disabled
test_not_verify_checksum "test_disabled_not_verify.log"
test_verify_checksum "test_disabled_verify.log"
