#!/bin/bash
#
# DKIM
# -------------------------------------------------------------------
#
echo -e "\n  start $0_dkim"

[ "X${SOMETHING_CHANGED:-}" = "X" ] && {
	echo -e "\nerror: this script cannot be run standalone, is part," >&2
	echo -e "   and is sourced, from main 'run-install' script" >&2
	exit 1
}

NoParse='false'

save_SOMETHING_CHANGED=$SOMETHING_CHANGED; SOMETHING_CHANGED=false

if getconfirm srv-mail.use_dkim
then
	dkim_dir="$postfixdir/dkim.d"
	dkim_local="/etc/kusa/modules/local/postfix_dkim"
	localinstall="/etc/kusa/modules/local/install"

	[ -d $dkim_local ] || {
		create_dir "$dkim_local" root:root 2770
		putwarning "POSTFIX DKIM: $dkim_local (dir)" \
			"a new config directory has been created to store" \
			"custom (machine dependent) POSTFIX DKIM files"
	}

	grep -q 'postifx_dkim' $localinstall || {
		(
		  echo
		  echo "# postfix (DKIM) section"
	  	  echo ":default_mode	440"
	  	  echo "postfix_dkim/*		/etc/postfix/dkim.d/"
		) >>$localinstall
	} || :

	dkim_user=$(jtconf dkim.user 2>/dev/null || echo "opendkim")
	dkim_group=$(jtconf dkim.group 2>/dev/null || echo "opendkim")
	dkim_owner="$dkim_user:$dkim_group"

	# install empty config files if needed
	#
	for file in trusted_hosts
	do
		[ -f "$dkim_dir/$file" ] || {
			installfile "dkim/$file" "$dkim_dir/" $dkim_owner 440 || exit_err $? "installing $file"
		}
		# one copy in kusa localdir
		[ -f $dkim_local/$file ] || {
			installfile "dkim/$file" "$dkim_local/" root:root 660 $NoParse || exit_err $? "installing $file"
		}
	done

	installfile dkim/dkim_setup		/etc/postfix/dkim_setup $dkim_owner 770
	installfile dkim/opendkim.conf		/etc/ root:root 440
	installfile dkim/opendkim.default	/etc/default/opendkim root:root 440

	(cd /etc/postfix; ./dkim_setup -x) || {
		err=$?
		[ $err != 254 ] && exit_err $err "$err from dkim_setup"
		SOMETHING_CHANGED=true
	}

	# make sure that postfix can read opendkim unix socket, if needed
	#
	grps=$(getent group opendkim | cut -d':' -f4)
	id postfix | fgrep -q '(opendkim)' || {
		echo -n "  adding 'postfix' to group 'opendkim': "
		usermod -G opendkim --append postfix
		id postfix
	}
else
	uninstallfiles \
		/etc/postfix/dkim_setup \
		/etc/opendkim.conf \
		/etc/opendkim.default

fi # getconfirm srv-mail.use_dkim

# -------------------------------------------------------------------
changed_dkim=$SOMETHING_CHANGED; $save_SOMETHING_CHANGED && SOMETHING_CHANGED=true

echo "  done $0_dkim"
# run-install_dkim (eof)
