#!/bin/sh

set -e
set -o xtrace

export DEBIAN_FRONTEND=noninteractive

cat > "/etc/sysctl.d/10-postgresql-performance.conf" << _EOF_
# See 'http://www.postgresql.org/docs/9.4/static/kernel-resources.html'
# for best practices.
# It is recommended to disable memory overcommit,
# but the Python interpreter may require it on smaller flavors.
# We therefore stick with the heuristic overcommit setting.
vm.overcommit_memory=0
vm.nr_hugepages=64

_EOF_

cat > "/etc/rc.local" << _EOF_
# See 'http://www.postgresql.org/docs/9.4/static/kernel-resources.html'
# Postgres 9.4 added support for THP. Using huge pages reduces overhead when
# using large contiguous chunks of memory, like PostgreSQL does.
if test -f /sys/kernel/mm/transparent_hugepage/defrag; then
  echo never > /sys/kernel/mm/transparent_hugepage/defrag
fi
if test -f /sys/kernel/mm/transparent_hugepage/enabled; then
  echo always > /sys/kernel/mm/transparent_hugepage/enabled
fi

exit \$?

_EOF_

apt-get -y install postgresql-9.4 postgresql-contrib-9.4 postgresql-server-dev-9.4

###########################################
# Hack alert:
# For Postgresql 9.4, pg_rewind is not in the main source tree and
# no packages exist in the repos, so it must be compiled manually
# and installed on the image until we can move to 9.5
# See README at
# https://github.com/vmware/pg_rewind/tree/REL9_4_STABLE

tmpdir=/tmp/build
mkdir -p $tmpdir
cd $tmpdir
git clone https://github.com/postgres/postgres.git --branch REL9_4_STABLE
cd postgres/contrib
git clone https://github.com/vmware/pg_rewind.git --branch REL9_4_STABLE

dev_pkgs="libreadline-dev libkrb5-dev libssl-dev libpam-dev libxml2-dev libxslt-dev libedit-dev libselinux1-dev bison flex"

apt-get install $dev_pkgs -y

# Unfortunately, on ubuntu, was not able to get pg_rewind to build
# outside of the pgsql source tree. Configure and compile postgres
# but only call make install against the contrib/pg_rewind directory
# so that support library is accessible to the server
cd $tmpdir/postgres
./configure 
make
cd contrib/pg_rewind
make install

# Make the pg_rewind binary and the library used by the 
# pg_rewind stored procedures accessible
ln -s /usr/local/pgsql/bin/pg_rewind /usr/bin/pg_rewind
ln -s /usr/local/pgsql/lib/pg_rewind_support.so /usr/lib/postgresql/9.4/lib/pg_rewind_support.so

cd
rm -rf $tmpdir
apt-get remove -y $dev_pkgs

# End hack
################################

# Install the native Python client.
apt-get -y install libpq-dev
pip install psycopg2
