#!/bin/bash
set -o errexit -o nounset -o pipefail

function main {
  case "${1:-${TRAVIS_OS_NAME:-}}" in
    linux) linux ;;
    osx)   osx ;;
    *)     echo "No handler for: ${1:-}" >&2
  esac
}

function tools {
  cargo install rustfmt
  sudo pip install pgxnclient
}

function hba {
cat <<\EOF
local    replication     all trust
host     replication     all ::1/128 trust
EOF

}

function conf {
cat <<\EOF
max_wal_senders = 1
wal_level = logical
max_replication_slots = 1
EOF
}

function linux {
  tools

  VERSION=9.4
  PG_DIR=/etc/postgresql/"$VERSION"/main
  HBA_CONF="$PG_DIR"/pg_hba.conf
  CONF="$PG_DIR"/postgresql.conf
  (cd jsoncdc; sudo -E env PATH="$PATH" LD_LIBRARY_PATH="$LD_LIBRARY_PATH"  make install)
  sudo pg_ctlcluster "$VERSION" main stop

  msg "Setting $HBA_CONF settings..."
  hba | sudo tee -a "$HBA_CONF"
  msg "Setting $CONF settings..."
  conf | sudo tee -a "$CONF"
  sudo pg_ctlcluster "$VERSION" main start
}

function osx {
  tools

  BREW_LOG=brew.log
  PG_DIR=/usr/local/var/postgres/
  PG_LOG="$PG_DIR"/server.log
  HBA_CONF="$PG_DIR"/pg_hba.conf
  CONF="$PG_DIR"/postgresql.conf
  TIMEOUT=60

  pg_ctl -D "$PG_DIR" stop -s -m fast -t "$TIMEOUT" || true
  msg 'Removing old Postgresql...'
  rm -rf "$PG_DIR"

  brew update > "$BREW_LOG"
  brew remove postgresql >> "$BREW_LOG"
  brew upgrade >> "$BREW_LOG"

  (cd jsoncdc; make clean all install)

  msg "Setting $HBA_CONF settings..."
  hba >> "$HBA_CONF"
  msg "Setting $CONF settings..."
  conf >> "$CONF"

  pg_ctl -D "$PG_DIR" -l "$PG_LOG" -w -t "$TIMEOUT" start

  STARTED=false
  while ! "$STARTED"
  do
    pg_ctl status -D "$PG_DIR" && STARTED=true
    sleep 1
  done
}


##################################################################### Utilities

function msg { out "$*" >&2 ;}
function err { local x=$? ; msg "$*" ; return $(( $x == 0 ? 1 : $x )) ;}
function out { printf '%s\n' "$*" ;}

# Handles "no-match" exit code specified by POSIX for filtering tools.
function maybe { "$@" || return $(( $? == 1 ? 0 : $? )) ;}


######################### Delegates to subcommands or runs main, as appropriate

if declare -f -- "${1:-}" >/dev/null
then "$@"
else main "$@"
fi
