#!/bin/sh -ue

# At this time, while this script is trivial, we ignore any parameters given.
# However, for backwards compatibility reasons, future versions of this script must
# support the syntax "update-ca-trust extract" trigger the generation of output
# files in $EXTRACT_DIRECTORY.

DEFAULT_EXTRACT_DIR=/etc/pki/ca-trust/extracted
PROG="${0##*/}"
EXTRACT_DIR=

# Prevent p11-kit from reading user configuration files.
export P11_KIT_NO_USER_CONFIG=1

usage()
{
	fold -s -w 76 >&2 <<-EOF
		Usage: $PROG [extract] [-o DIR|--output=DIR]

		Update the system trust store in $DEFAULT_EXTRACT_DIR.

		COMMANDS
		(absent/empty command): Same as the extract command described below.

		extract: Instruct update-ca-trust to scan the source configuration in
		/usr/share/pki/ca-trust-source and /etc/pki/ca-trust/source and produce
		updated versions of the consolidated configuration files stored below
		the $DEFAULT_EXTRACT_DIR directory hierarchy.

		EXTRACT OPTIONS
		-o DIR, --output=DIR: Write the extracted trust store into the given
		directory instead of updating $DEFAULT_EXTRACT_DIR.
	EOF

	exit $1
}


error()
{
	echo >&2 "$PROG: $1"
}

fatal()
{
	error "$@"
	usage 1
}

###############################################################################
if [ $# -gt 0 ] && [ "$1" = "extract" ]; then
	# 'extract' command is optional
	shift 1
fi

while [ $# -ne 0 ]; do
	case "$1" in
		"-o"|"--output")
			if [ $# -lt 2 ]; then
				fatal "--output requires an argument"
			fi
			EXTRACT_DIR="$2"
			shift 2
			continue
			;;
		"--")
			shift
			break
			;;
		"-h"|"--help")
			usage 0
			;;
		*)
			fatal "unrecognized option: $1"
			;;
	esac
done

[ -n "$EXTRACT_DIR" ] || EXTRACT_DIR="$DEFAULT_EXTRACT_DIR"
export EXTRACT_DIR DEFAULT_EXTRACT_DIR
ret=0
for f in /usr/libexec/ca-trust/update.d/*.hook; do
	[ -f "$f" -a -x "$f" ] || continue

	"$f" "$@" || {
		error "${f##*/} failed"
		ret=1
	}
done
exit $ret
