#!/bin/bash

# check_check.sh
#
# Create a regular database cluster and one with checksums.
# Corrupt a bit of data in each, to see if the checksummed
# version catches it.
#
# Requires that PGDATA is set to the cluster location.
# ** This will erase everything in your PGDATA directory! **
#
# Greg Smith <greg@2ndquadrant.com>
# Copyright (c) 2013, Heroku, Inc.
# Released under The PostgreSQL Licence

if [ ! -d $PGDATA ] ; then
  echo Cannot run without correctly set PGDATA
  exit 1
fi

PGLOG="$PGDATA/pg.log"

function stop {
  if [ -f "$PGDATA/postmaster.pid" ] ; then
    pg_ctl stop -D $PGDATA -m immediate
  else
    echo "Server doesn't appear started"
  fi
}

function start {
  if [ -f "$PGDATA/postmaster.pid" ] ; then
    echo "Server appears started:"
    ls -l $PGDATA/postmaster.pid
  else
    pg_ctl start -D $PGDATA -l $PGLOG -w
    tail $PGLOG
  fi
}

function corrupter {

  pg_controldata | grep checksum
  start
  createdb `whoami`
  pgbench -i -s 1
  stop
  start
  ./pg_corrupt pgbench_accounts xor 14 1
  stop
  start
  # Show doesn't accept an offset yet, but it should
  #./pg_corrupt pgbench_accounts show 14

  # Uses of count() or calculations on aid can use an index only scan.
  # Force touching every data row by touching a non-indexed column.
  psql -c "select sum(abalance) from pgbench_accounts"

}

# Validate current behavior without checksums
stop
rm -rf $PGDATA/*
initdb
corrupter

# Create a checksummed database and introduce the same error
stop
rm -rf $PGDATA/*
initdb -k
corrupter
