#!/bin/bash
 
TMPDIR=/dev/shm

if [[ -z $1 ]]; then
	PGPORT=5432
else
	PGPORT=$1
fi

cache_prefix=$TMPDIR/zabbix-pg_stat_database-${PGPORT}

/usr/bin/sudo -u postgres /usr/bin/psql -p $PGPORT -d postgres -tc "copy (select * from pg_stat_database where datname not like 'template%' and datname not like 'postgres') to stdout delimiter ';' csv;" > ${cache_prefix}.tmp
if [[ $? -ne 0 ]]; then
	echo "1"
	exit 1
else
	rsync -t ${cache_prefix}.tmp ${cache_prefix}.cache
	if [[ $? -ne 0 ]]; then
		echo "1"
		exit 1
	fi
fi
echo "0"
