#!/bin/bash

. ${TOOLKIT}-functions.sh

# get version and record it in kusa-conf autofile
#
autofile="/etc/kusa/conf.d/auto.00.srv-pgsql"
pgrelese=

case $DISTRIB_FULL_ID in
  Ubuntu-12.04)	pgrelease="9.1" ;;
  Devuan-1.0)	pgrelease="9.4" ;;
esac
echo "  system release $DISTRIB_FULL_ID, using postgresql $pgrelease"
echo "  (recorded in $autofile, you can override it in /etc/kusa/kusa.conf)"
echo "# $autofile
[pgsql]
  release	$pgrelease
" >$autofile

release=`jtconf pgsql.release`	|| exit_missing_define pgsql.release

[ "$release" != "$pgrelease" ] && {
	echo "  release override, using $release instead"
}

#----------------------------------------------------------------
# build pg_hba.conf
#----------------------------------------------------------------

echo "  building host based access file (pg_hba.conf) ..."

outfile=tmppg_hba.tmp
orig=/etc/postgresql/$release/main/pg_hba.conf
orig=pg_hba.conf

cp $orig $outfile || exit $?

myself=`uname -n`
myself_short=`uname -n | sed -e 's/\..*//'`

comment="# entries added by kusa"

# elimina le righe precedentemente create (comprese tra
# $comment ... START e $comment END)
#
copy=true
cat $outfile | while read line
do
	case "$line" in
		${comment}*START)	copy=false ;;
		${comment}*END)		copy=true ; continue ;;
	esac
	$copy && echo "$line"
done >$outfile.1.tmp
mv $outfile.1.tmp $outfile || exit $?


echo "$comment START" >>$outfile

# cerca nelle sezioni [pgsql_hba.xxxx] le eventuali definizioni per
# tutti gli hosts (*) e se stesso (hostname)
#
for section in `jtconf --list pgsql_hba.`
do
	database=`	jtconf $section.database`	|| exit_missing_define $section.database
	user=`		jtconf $section.user`		|| exit_missing_define $section.user
	address=`	jtconf $section.address`	|| exit_missing_define $section.address
	conntype=`	jtconf $section.conntype`	|| exit_missing_define $section.conntype
	method=`	jtconf $section.method`		|| exit_missing_define $section.method
	options=`	jtconf $section.options 2>/dev/null`	|| :
	include=`	jtconf $section.include 2>/dev/null`	|| :
	exclude=`	jtconf $section.exclude 2>/dev/null`	|| :

	# is include?
	[ "$include" ] && {
		must_include=false
		for match in `echo "$include" | tr ',' ' '`
		do
			case $myself_short in
				$match) must_include=true ; break ;;
			esac
			case $myself in
				$match) must_include=true ; break ;;
			esac
		done
		$must_include || continue	# next entry
	}

	# is excluded?        (myself always exluded)
	[ "$exclude" ] && {
		must_exclude=false
		for match in `echo "$exclude" | tr ',' ' '` $myself
		do
			case $myself_short in
				$match) must_exclude=true ; break ;;
			esac
			case $myself in
				$match) must_exclude=true ; break ;;
			esac
		done
		$must_exclude && continue	# next entry
	}

	fmt="%.7s %-11s %-11s %-21s %s\n"
	string=`printf "$fmt" $conntype $database $user $address $method`
	[ "$options" != "" ] && string="$string\t$options"
	echo -e "  $string"
	echo -e "$string" >>$outfile
done
echo "$comment END" >>$outfile

exit 0
