#! /bin/bash
#
# Written by sbrabec@suse.com
#
declare -a PRESET_FILES
declare -A PRESETS
declare -A PRESETS_OLD
declare -A PRESETS_OLD_WILDCARD
declare -A PRESETS_WILDCARD

save_preset_states () {
	PRESET_FILES=(*.preset)

	for ((i=${#PRESET_FILES[@]}-1 ; i>= 0 ; i-- )) ; do
		FILE=${PRESET_FILES[i]}
		exec 3<"$FILE"
		while read -u3 ENABLE SERVICE PAD ; do
			if test -z "$SERVICE" ; then
				continue;
			fi
			case "$ENABLE" in
			enable|disable)
				PRESETS[$SERVICE]=$ENABLE;;
			esac
		done
		exec 3<&-
	done
	exec 3>systemd_preset-old.rpm-tmp
	for PRESET in "${!PRESETS[@]}" ; do
		echo >&3 "${PRESETS[$PRESET]} $PRESET"
	done
	exec 3>&-
}

apply_preset_state_changes () {
	if ! test -f systemd_preset-old.rpm-tmp ; then
		return
	fi
	exec 3<systemd_preset-old.rpm-tmp
	while read -u3 ENABLE SERVICE PAD ; do
		if test -z "$SERVICE" ; then
			continue
		fi
		case "$ENABLE" in
		enable|disable)
			case $SERVICE in
			*"*"*|*"?"*) PRESETS_OLD_WILDCARD[$SERVICE]=$ENABLE;;
			*) PRESETS_OLD[$SERVICE]=$ENABLE;;
			esac
		esac
	done
	exec 3<&-
	PRESET_FILES=(*.preset)
	for ((i=${#PRESET_FILES[@]}-1 ; i>= 0 ; i-- )) ; do
		FILE=${PRESET_FILES[i]}
		exec 3<"$FILE"
		while read -u3 ENABLE SERVICE PAD ; do
			if test -z "$SERVICE" ; then
				continue
			fi
			case "$ENABLE" in
			enable|disable)
				case $SERVICE in
				*"*"*|*"?"*) PRESETS_WILDCARD[$SERVICE]=$ENABLE;;
				*) PRESETS[$SERVICE]=$ENABLE;;
				esac
			esac
		done
		exec 3<&-
	done
	if test -x /usr/bin/systemctl ; then
		/usr/bin/systemctl list-unit-files $GLOBAL
	fi >systemd_preset-states.rpm-tmp
	exec 3<systemd_preset-states.rpm-tmp
	read -u3 PAD
	while read -u3 SERVICE ENABLE PAD ; do
		if test -z "$SERVICE" ; then
			break
		fi
		# FIXME: This is not strictly correct as associative
		# arrays are not ordered.
		ENABLE_OLD=enable
		for PRESET in "${!PRESETS_OLD_WILDCARD[@]}" ; do
			case "$SERVICE" in
			$PRESET) ENABLE_OLD=${PRESETS_OLD_WILDCARD[$PRESET]};;
			esac
		done
		if test -n "${PRESETS_OLD[$SERVICE]}" ; then
			ENABLE_OLD="${PRESETS_OLD[$SERVICE]}"
		fi
		ENABLE_NEW=enable
		for PRESET in "${!PRESETS_WILDCARD[@]}" ; do
			case "$SERVICE" in
			$PRESET) ENABLE_NEW=${PRESETS_WILDCARD[$PRESET]};;
			esac
		done
		if test -n "${PRESETS[$SERVICE]}" ; then
			ENABLE_NEW="${PRESETS[$SERVICE]}"
		fi
		if test "$ENABLE_OLD" != "$ENABLE_NEW" ; then
			echo "Resetting $SERVICE to the new default: $ENABLE_NEW"
			/usr/bin/systemctl preset $GLOBAL "$SERVICE" || :
		fi
	done
	exec 3<&-
	rm -f systemd_preset-{old,states}.rpm-tmp
}


if test "$2" == "user" ; then
  cd /usr/lib/systemd/user-preset
  GLOBAL="--global"
else
  cd /usr/lib/systemd/system-preset
  GLOBAL=""
fi

case $1 in
apply-changes)
	apply_preset_state_changes ;;
save)
	save_preset_states ;;
*)
	echo >&2 "Unkown command '$1'"
	exit 1
esac
