#!/bin/sh

set -eux

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

if [ -z "$(pg_lsclusters -h)" ]; then
  version=$(ls /usr/lib/postgresql -v | tail -1)
  pg_createcluster $version main
fi

service postgresql start
if test -d /run/systemd/system; then
  systemctl stop pgagroal pgagroal.socket
  # socket activation is broken (https://github.com/pgagroal/pgagroal/issues/736), test only the .service for now:
  systemctl start pgagroal.service
else
  su -c 'pgagroal' postgres &
fi

PW=agroalpass
su -c "dropuser --if-exists agroaltestuser" postgres
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
