#!/bin/sh

set -e
set -o xtrace

cat > "/etc/sysctl.d/10-postgresql-performance.conf" << _EOF_
# See 'http://www.postgresql.org/docs/9.6/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

_EOF_

cat > "/etc/rc.local" << _EOF_
#!/bin/bash

# See 'http://www.postgresql.org/docs/9.6/static/kernel-resources.html'
# Disable Linux kernel transparent huge pages. This feature is not supported by
# by Postgres 9.6 and may negatively impact performance of the database.
if test -f /sys/kernel/mm/redhat_transparent_hugepage/defrag; then
  echo never > /sys/kernel/mm/redhat_transparent_hugepage/defrag
fi
if test -f /sys/kernel/mm/redhat_transparent_hugepage/enabled; then
  echo never > /sys/kernel/mm/redhat_transparent_hugepage/enabled
fi

exit \$?

_EOF_

dnf install -y https://yum.postgresql.org/9.6/fedora/fedora-27-x86_64/pgdg-fedora96-9.6-4.noarch.rpm

dnf install -y postgresql96-server postgresql96-contrib postgresql96-devel gcc

# Though /var/lib/pgsql is the preferred directory, need to move it as
# this is where the volume will be mounted
su - postgres -c "/usr/pgsql-9.6/bin/initdb /var/lib/pgsql/9.6/data"
mv /var/lib/pgsql /var/lib/postgresql

# The `postgresql96-setup` use postgresql-${MAJORVERSION} as the service name,  so rename 
# postgresql-9.6.service to postgresql.service is not a good idea. 
#mv /lib/systemd/system/postgresql-9.6.service /lib/systemd/system/postgresql.service

sed -i 's/PGDATA=\/var\/lib\/pgsql\/9.6\/data/PGDATA=\/var\/lib\/postgresql\/9.6\/data/' /lib/systemd/system/postgresql-9.6.service

# Set the right log location for PGUPLOG and PGLOG.
sed -i 's/\/var\/lib\/pgsql/\/var\/lib\/postgresql/' /usr/pgsql-9.6/bin/postgresql96-setup

# Add all postgresql related command(include pg_rewind) to the OS path.
export PATH=$PATH:/usr/pgsql-9.6/bin

# Install the native Python client.
dnf install -y postgresql-devel python-devel
pip install psycopg2

# Run initdb before `systemctl start`
/usr/pgsql-9.6/bin/postgresql96-setup initdb
systemctl enable postgresql-9.6.service
systemctl start postgresql-9.6.service
