#!/bin/bash

# dependencies

function check-postgresql-localhost-deps {
	if [ ! -e /usr/bin/pg_dump ]; then
		debug "It seems that you dont have psql installed. You may have problems to backup remote databases"
	fi
	numberRegex='^[0-9]+$'
	if ! [[ $(id -u postgres 2>&1) =~ $numberRegex ]] ; then
		debug "It seems that you dont have the user postgres on your computer. You may have problems to backup local postgres databases"
	fi
}

# PostgreSQL local

function pg_local_all {
	# Debugoutput id DEBUG is enabled
	debug "Dump all from Postgres local"
	# Dump all databases in one file as user postgres (Debian)
	sudo -H -u postgres pg_dumpall > "$TMP_DIR"/local_dumpall.pgsql
	debug "Diff alldumps from Postgres local"
	# Check if there are differences between the actual dump and the last dump
	backup_file_handler "$TMP_DIR" "$BACKUP_DIR" local_dumpall.pgsql
}

function pg_local_single {
	# Get a list with all databases on localhost. Do it as user postgres (Debian)
	# parallelize the following
	for DB in $(sudo -H -u postgres /usr/bin/psql -At -c "SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn ORDER BY datname;" postgres)
		do
			debug "Dumping local database $DB"
			# Dump each database in a single file
			sudo -H -u postgres /usr/bin/pg_dump -Fp "$DB" > "$TMP_DIR"/local_"$DB".pgsql
			backup_file_handler "$TMP_DIR" "$BACKUP_DIR" local_"$DB".pgsql
			echo ""
		done
}

# Do the local backupjobs

function run_local_pg_backups {
	# Test if the current backupuser has access via sudo to postgres
	# This part has to be improved!
	sudo -l -U "$BACKUPUSER" | grep postgres
	if [ $? -eq 0 ];then
		# If the user has access vi sudo to postgres and a full dump is configured, do it.
		if [ "$POSTGRES_BACKUP_LOCAL_DUMP_ALL" == "TRUE" ]; then
			pg_local_all
		fi
		# If the user has access vi sudo to postgres and dumps for each database is configured , do it.
		if [ "$POSTGRES_BACKUP_LOCAL_SINGLE" == "TRUE" ]; then
			pg_local_single
		fi
	else
		# If the user is not permitted to acces the postgresdatabases vi sudo throw an errormessage
		echo "" | $LOGGER
		echo "The backupuser does not the permission to act as user postgres" | $LOGGER
		echo "Please add the following line to your /etc/sudoers:" | $LOGGER
		echo "backupuser ALL=(postgres) NOPASSWD:/usr/bin/psql,/usr/bin/pg_dump,/usr/bin/pg_dumpall" | $LOGGER
		echo "" | $LOGGER
	fi
}

################################################################################


function postgresql-localhost-main {
	if [ "$POSTGRES_BACKUP_LOCAL" = "TRUE" ]; then
		run_local_pg_backups
	fi
}
