#!/bin/bash

# Unofficial Bash Strict Mode
# http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -euo pipefail
IFS=$'\n\t'
# End of Unofficial Bash Strict Mode

# Common colors
c_reset=$'\e[0m'
c_date=$'\e[0;35m'
c_progress=$'\e[0;1;32m'

progress() {
    txt="${1:-??}"
    echo "${c_date}$( date '+%Y-%m-%d %H:%M:%S' )${c_reset} : ${c_progress}${txt}${c_reset}"
}

cd /home/pgdba

progress "Stopping Pg"
pg_ctl -w -m immediate stop || true

progress "Removing Pg"
rm -Rf "${PGDATA}"/* work/* src/pgsql

progress "Fetching newest PG sources"
cd ~/src/git/postgresql
time git pull --rebase -q
cd ~/src
cp -a git/postgresql pgsql

progress "Configuring sources"
cd pgsql
time ~/src/dev-configure.sh

jobs_count="$( nproc )"

progress "Compiling Pg"
time make -s -j "${jobs_count}"

progress "Installing Pg"
time make -s -j "${jobs_count}" install

cd contrib
progress "Compiling contrib"
time make -s -j "${jobs_count}"
progress "Installing contrib"
time make -s -j "${jobs_count}" install

cd ~

progress "Fetching documentation for dev Pg"
TEMPDIR=$( mktemp -d )
trap 'rm -rf "${TEMPDIR}"' EXIT
time wget -q -O "${TEMPDIR}"/docs.tar.bz2 https://ftp.postgresql.org/pub/snapshot/dev/postgresql-snapshot.tar.bz2

progress "Installing documentation for dev pg"
tar xjf "${TEMPDIR}"/docs.tar.bz2 -C "${TEMPDIR}"/ --wildcards postgresql-*/doc/src/sgml/html postgresql-*/doc/src/sgml/man?
mkdir -p work/share/doc/postgresql/
rm -rf work/share/doc/postgresql/html
mv "${TEMPDIR}"/postgresql-*/doc/src/sgml/html work/share/doc/postgresql/
mkdir -p work/share/man
mv "${TEMPDIR}"/postgresql-*/doc/src/sgml/man? work/share/man/
rm -rf "${TEMPDIR}"

progress "Running initdb"
time initdb -E UTF8 -A trust > /dev/null

progress "Fixing configuration"
cat ~/src/configs/pg_hba.conf > "${PGDATA}/pg_hba.conf"
cat ~/src/configs/postgresql.auto.conf > "${PGDATA}/postgresql.auto.conf"

progress "Starting new Pg"
pg_ctl -w start

progress "Remove obsolete sources"
rm -Rf /home/pgdba/src/pgsql

progress "Some final touches to allow easier work"
createdb pgdba
createuser -s postgres

progress "All done."
