#!/bin/bash

# fail-peer.sh
#
# This script is provided for debugging purposes.  It should not be used for deploying Bucardo or Postgres, as it has not been vetted for safe Postgres security practices.
#
# This script is meant to be run on a fresh and patched Ubuntu 14.04 virtual machine with an administrator-privileged account.  It was tested on an up-to-date Ubuntu 14.04 VM with patches up to date and openssh-server installed.
#
# This version of the script FAILS at the end.  There is an issue with peer authentication.
#
# Author: AJN 2015-07-20

set -x
set -e

# Install packages.

sudo apt-get install -y \
  bucardo \
  postgresql

# Set superuser password.  The bucardo installation script prompts for the 'postgres' user password on each operation.
# (This is but one reason this is not a Bucardo deployment script.)
set +x
echo -n "Enter a password to use for Postgres superuser (MAY BE VISIBLE AFTER ENTRY):"
read -s postgres_superuser_password
echo
sudo -u postgres psql -U postgres <<EOF
ALTER USER postgres WITH PASSWORD '${postgres_superuser_password}';
EOF
set -x

# Make bucardo's default run directory.
if [ ! -d /var/run/bucardo ]; then
  sudo mkdir -p /var/run/bucardo
  sudo chown -R bucardo:bucardo /var/run/bucardo
fi

# Insert the bucardo authentication lines into pg_hba, BEFORE the 'all' catch-all rules.
pg_hba=/etc/postgresql/9.3/main/pg_hba.conf
if [ $(sudo grep 'bucardo' $pg_hba | wc -l) -eq 0 ]; then
  #sed insert c/o https://stackoverflow.com/a/11695086
  sudo sed -i '/# TYPE  DATABASE/i \
local bucardo bucardo peer' "$pg_hba"

  #This line appears in the shell transcript if restarting before Bucardo's installation is complete:
  #
  #    NOTICE:  database "bucardo" does not exist, skipping
  #
  #Restarting Postgres after Bucardo installation doesn't fix the problem, unfortunately.
  sudo service postgresql restart
fi

# Reset bucardo-related data in case this script is re-run while testing.
sudo -u postgres psql -U postgres <<EOF
DROP DATABASE IF EXISTS bucardo;
CREATE DATABASE bucardo;
EOF

sudo -u bucardo HOME=~bucardo bucardo install

# Restart Postgres, attempting to catch Bucardo authentication rule.
sudo service postgresql restart

# Check that ~bucardo/.pgpass exists.
sudo ls -la ~bucardo/.pgpass

# Check that bucardo runs.  (FAILS.  Authentication issue.)
sudo -u bucardo bucardo status
