#!/bin/sh

set -eux

# if running as root, we need to tweak ~postgres/.pgpass
if [ "$(id -un)" = "root" ]; then
	export PGPASSFILE="/var/lib/postgresql/.pgpass"
	su -c "touch $PGPASSFILE" postgres # create file if it doesn't exist yet
	chmod 600 $PGPASSFILE
else
	export PGPASSFILE="$HOME/.pgpass"
fi
trap "sed -i -e '/# added by pg_cron testsuite/,$ d' $PGPASSFILE" 0 2 3 15

for ver in $(pg_buildext installed-versions); do
	pg_virtualenv -v $ver -o 'shared_preload_libraries=pg_cron' <<-'EOT'
		set -eux
		umask 077
		echo "# added by pg_cron testsuite" >> $PGPASSFILE
		echo "localhost:$PGPORT:$PGDATABASE:$PGUSER:$PGPASSWORD" >> $PGPASSFILE
		psql -eX <<-'EOF'
			\set ON_ERROR_STOP
			CREATE EXTENSION pg_cron VERSION '1.0'; -- 9.x can't directly install 1.2 because that only exists as upgrade path
			ALTER EXTENSION pg_cron UPDATE;
			SELECT cron.schedule('* * * * *', 'CREATE TABLE foo()');
			SELECT * FROM cron.job;
			SELECT pg_sleep(70);
			SELECT * FROM foo;
		EOF
	EOT
	sed -i -e '/# added by pg_cron testsuite/,$ d' $PGPASSFILE
done
