#!/bin/sh -e
#
# 2020 Dennis Camera (dennis.camera at ssrq-sds-fds.ch)
#
# This file is part of cdist.
#
# cdist is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cdist is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cdist. If not, see <http://www.gnu.org/licenses/>.
#

joinlines() { sed -n -e H -e "\${x;s/^\\n//;s/\\n/${1:?}/g;p;}"; }

state_is=$(cat "${__object:?}/explorer/state")
state_should=$(cat "${__object:?}/parameter/state")

if test "${state_is}" = "${state_should}" -o "${state_is}" = 'default'
then
	# nothing to do (if the value is the default, ignore its state)
	exit 0
fi

case ${state_should}
in
	(present)
		mode='set'
		;;
	(absent)
		mode='unset'
		;;
	(*)
		printf 'Invalid --state: %s\n' "${state_should}" >&2
		exit 1
		;;
esac

sshd_config_file=$(cat "${__object:?}/parameter/file")

quote() { printf "'%s'" "$(printf '%s' "$*" | sed -e "s/'/'\\\\''/g")"; }
drop_awk_comments() { quote "$(sed '/^[[:blank:]]*#.*$/d;/^$/d' "$@")"; }

# Ensure the sshd_config file is there
cat <<EOF
test -e $(quote "${sshd_config_file}") || {
	 : >$(quote "${sshd_config_file}")
	 chown 0:0 $(quote "${sshd_config_file}")
	 chmod 0644 $(quote "${sshd_config_file}")
}

EOF

match_only=
if test -s "${__object:?}/parameter/match"
then
	match_only=$(joinlines ' ' <"${__object:?}/parameter/match")
fi

if test -s "${__object:?}/parameter/option"
then
	option_line=$(cat "${__object:?}/parameter/option")
else
	option_line=${__object_id:?}
fi

if test -s "${__object:?}/parameter/value"
then
	option_line="${option_line} $(cat "${__object:?}/parameter/value")"
fi

# Send message on config update
printf '%s%s %s\n' "${mode}" "${match_only:+ [${match_only}]}" \
	"${option_line}" >>"${__messages_out:?}"

# Update sshd_config (remote code)
cat <<EOF
awk $(drop_awk_comments "${__type:?}/files/update_sshd_config.awk") \\
	-o ${mode} \\
	-m $(quote "${match_only}") \\
	-l $(quote "${option_line}") \\
	$(quote "${sshd_config_file}") >$(quote "${sshd_config_file}.tmp") \\
|| exit

cmp -s $(quote "${sshd_config_file}") $(quote "${sshd_config_file}.tmp") || {
	sshd -t -f $(quote "${sshd_config_file}.tmp") \\
	&& cat $(quote "${sshd_config_file}.tmp") >$(quote "${sshd_config_file}") \\
	|| exit  # stop if sshd_config file check fails
}
rm -f $(quote "${sshd_config_file}.tmp")
EOF
