#!/bin/sh -e
# -*- mode: sh; indent-tabs-mode: t -*-
#
# 2019 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/>.
#

version_ge() {
	awk -F '[^0-9.]' -v target="${1:?}" '
	function max(x, y) { return x > y ? x : y; }
	BEGIN {
		getline;
		nx = split($1, x, ".");
		ny = split(target, y, ".");
		for (i = 1; i <= max(nx, ny); ++i) {
			diff = int(x[i]) - int(y[i]);
			if (diff < 0) exit 1;
			else if (diff > 0) exit 0;
			else continue;
		}
	}'
}

not_supported() {
	echo "OS ${os} does not support __sensible_editor." >&2
	echo 'If it does, please provide a patch.' >&2
	exit 1
}

os=$(cat "${__global}/explorer/os")
os_version=$(cat "${__global}/explorer/os_version")

state=$(cat "${__object}/parameter/state")
user=$__object_id

if test "${state}" != 'present' && test "${state}" != 'exists' && test "${state}" != 'absent'
then
	echo 'Only "present", "exists", and "absent" are allowed for --state' >&2
	exit 1
fi

package_name='sensible-utils'

case $os
in
	debian)
		pkg_type='apt'
		;;
	devuan)
		pkg_type='apt'
		;;
	ubuntu)
		(echo "${os_version}" | version_ge 10.04) || package_name='debianutils'
		pkg_type='apt'
		;;
	centos|fedora|redhat|scientific)
		pkg_type='yum'
		;;
	*)
		not_supported
		;;
esac

if test "${state}" != 'absent'
then
	__package "${package_name}" --state present \
		--type "${pkg_type}"
	export require="__package/${package_name}"
fi

editor_path=$(cat "${__object}/explorer/editor_path")
user_home=$(cat "${__object}/explorer/user_home")
group=$(cat "${__object}/explorer/group")

__file "${user_home}/.selected_editor" --state "${state}" \
	--owner "${user}" --group "${group}" --mode 0644 \
	--source - <<EOF
# Managed by cdist
SELECTED_EDITOR="${editor_path}"
EOF
