#!/bin/bash

# the ssh connection to use
sshconnect="ssh postgres@pg"

# the local location where the psql socket should be created
localsockdir=/var/lib/barman/run
localsockfile=$localsockdir/.s.PGSQL.5432

# the remote location where the postgresql unix socket resides
remotesockfile=/var/run/postgresql/.s.PGSQL.5432

#
# NO NEED TO CHANGE ANYTHING BELOW HERE!
#

# helper function that starts the socket forward
startsocketfwd() {
	socat -L ${localsockfile}.lock "UNIX-LISTEN:$localsockfile,reuseaddr,fork,unlink-early" EXEC:"$sshconnect socat STDIO UNIX-CONNECT\:$remotesockfile" &
	socatpid=$!
}

# helper functon that stops the socket forward
stopsocketfwd() {
	kill $socatpid
	wait $socatpid 2>/dev/null
}

# the small wrapper itself
bmwrapper() {
	startsocketfwd
	sleep 5
	/usr/bin/barman $*
	stopsocketfwd
}

# create the socket dir if not already exists
[ -d $localsockdir ] || mkdir -p $localsockdir

# here starts the magic ;)
bmwrapper $*
