#!/bin/sh

set -eux

bailout () {
  if test -d /run/systemd/system; then
    systemctl stop pgagroal pgagroal.socket
  else
    pkill pgagroal
  fi
}
trap bailout EXIT

service postgresql stop
if test -d /run/systemd/system; then
  systemctl start pgagroal.socket
else
  su -c 'pgagroal' postgres &
fi

pg_virtualenv -o'port=5432' <<EOF
  set -eux
  PW=agroalpass

  su -c "( echo \$PW; echo \$PW ) | createuser --pwprompt agroaltestuser" postgres
  PGPASSWORD=\$PW psql -h /run/postgresql -p 2345 -U agroaltestuser -c 'select 6*7' postgres | grep 42
EOF
