#!/bin/bash

# Required packages to compile:
#
# audit-libs-devel
# bzip2-devel
# elfutils-libelf-devel
# glibc-devel
# keyutils-libs-devel
# krb5-devel
# libcap-ng-devel
# libcom_err-devel
# libgcrypt-devel
# libgpg-error-devel
# libicu-devel
# libselinux-devel
# libstdc++-devel
# ncurses-devel
# openssl-devel
# pam-devel
# pcre-devel
# perl-devel
# perl-ExtUtils-Embed
# perl-ExtUtils-MakeMaker
# TODO: python-devel
# readline-devel
# systemd-devel
# xz-devel
# zlib-devel

# Setup the environment
. /etc/profile

set -o errexit
set -o nounset

# Setup the versions
MAJOR_VERSION=16
VERSION=16.13

# Concurrent make
JOBS="$(expr "$(getconf _NPROCESSORS_ONLN)" + 1)"

# Create temp build directory
TMPDIR="`mktemp -d /tmp/postgresql-${MAJOR_VERSION}-build.XXXXXXXXXX`"

# Untar the source code
tar -xj -C "${TMPDIR}" -f "/opt/postgresql-$MAJOR_VERSION/src/postgresql-$VERSION.tar.bz2"

cd "${TMPDIR}/postgresql-$VERSION"
./configure \
	--prefix="/opt/postgresql-$MAJOR_VERSION" \
	--sysconfdir="/etc/opt/postgresql-$MAJOR_VERSION" \
	--with-includes=/usr/include \
	--with-perl \
	--without-python \
	--with-pam \
	--with-systemd \
	--with-ssl=openssl
/usr/bin/gmake -j "$JOBS"

rm \
	"/etc/opt/postgresql-$MAJOR_VERSION" \
	"/opt/postgresql-$MAJOR_VERSION/bin" \
	"/opt/postgresql-$MAJOR_VERSION/include" \
	"/opt/postgresql-$MAJOR_VERSION/lib" \
	"/opt/postgresql-$MAJOR_VERSION/share" \
	-rf

# Install new version
/usr/bin/gmake -j "$JOBS" install

# Install documentation (includes man pages)
/usr/bin/gmake -j "$JOBS" install-docs

# Create sysconfdir
mkdir -m 755 "/etc/opt/postgresql-$MAJOR_VERSION"
cp -a "/opt/postgresql-$MAJOR_VERSION/share/psqlrc.sample" "/etc/opt/postgresql-$MAJOR_VERSION/psqlrc"

# Compile contrib modules
cd "${TMPDIR}/postgresql-$VERSION/contrib/citext"
/usr/bin/gmake -j "$JOBS"
/usr/bin/gmake -j "$JOBS" install
cd "${TMPDIR}/postgresql-$VERSION/contrib/cube"
/usr/bin/gmake -j "$JOBS"
/usr/bin/gmake -j "$JOBS" install
cd "${TMPDIR}/postgresql-$VERSION/contrib/earthdistance"
/usr/bin/gmake -j "$JOBS"
/usr/bin/gmake -j "$JOBS" install

# Remove the untarred source
cd "/opt/postgresql-$MAJOR_VERSION/src"
rm -rf "${TMPDIR}/postgresql-$VERSION"

# Fix permissions
chmod -R g-w "/opt/postgresql-$MAJOR_VERSION"

# Remove temp build directory
rmdir "${TMPDIR}"

# Success
cat "/opt/postgresql-$MAJOR_VERSION/src/build-success.txt"
