#!/bin/sh
# vim:syntax=sh noexpandtab
#
# update-ca-certificates
#
# Copyright (c) 2010,2013 SUSE Linux Products GmbH
# Copyright (c) 2020-2026 SUSE LLC
# Copyright (c) 2025 Georg Pfuetzenreuter
# Author: Ludwig Nussel
#
# Inspired by Debian's update-ca-certificates
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1301,
# USA.
#

statedir='/var/lib/ca-certificates'
hooksdir1='/etc/ca-certificates/update.d'
hooksdir2='/usr/lib/ca-certificates/update.d'
verbose=
destdir=/
fresh=

export statedir

help_and_exit()
{
	cat <<-EOF
		USAGE: $0 [OPTIONS]
		OPTIONS:
		  --verbose, -v       verbose output
		  --root <Directory>  Root directory to use (default: $destdir)
		  --fresh, -f         start from scratch
		  --help, -h          this screen
	EOF
	exit 0
}

args="$*"
while [ $# -gt 0 ]; do
	param="$1"
	arg="$2"
	test "$arg" = "${arg#-}" || arg=
	shift
	case "$param" in
		-v|--verbose) verbose='-v' ;;
		-f|--fresh) fresh='-f' ;;
		-r|--root) destdir="$arg"; shift
		if [ -z "$destdir" ]; then
			echo "-r option requires parameter <directory>"
			exit 1
		fi
	;;
	-h|--help) help_and_exit ;;
	-*) echo "invalid option: $param" >&2; exit 1 ;;
    esac
done

# set sane umask
umask 0222;

case "${TRANSACTIONAL_UPDATE}" in
	true|TRUE|yes|YES|1)
		[ -z "$verbose" ] || echo "transactional update in progress, not running any scripts" >&2
		: > /etc/pki/trust/.updated
		exit 0
	;;
esac
rm -f /etc/pki/trust/.updated

export destdir

install -d -m 0755 "${destdir}${statedir}"
# serialize calls if we can
if [ -z "$_CA_CERTIFICATES_LOCKED" ] && [ -x /usr/bin/flock ]; then
	export _CA_CERTIFICATES_LOCKED="1"
	# shellcheck disable=SC2086 # expected splitting
	set -- $args
	exec /usr/bin/flock "${destdir}${statedir}" "$0" "$@"
	printf 'failed to lock %s/%s\n\n' "$destdir" "$statedir" >&2
	exit 1
fi

find_hooks()
{
	for hooksdir in $hooksdir1 $hooksdir2; do
		for f in "$hooksdir"/*.run; do
			if [ -L "$f" ] || [ -f "$f" ]; then
				echo "${f##*/}" "$f"
			fi
		done
	done
}

# shellcheck disable=SC2162 # no backslashes expected
find_hooks | sort -k 1,1 -u | while read _ f; do
	if [ -L "$f" ] && [ "$(readlink "$f")" = '/dev/null' ]; then
		[ -z "$verbose" ] || echo "skipping $f"
		continue
	else
		[ -z "$verbose" ] || echo "running $f .."
	fi
	"$f" $fresh $verbose
done

chmod 0555 "${destdir}${statedir}"
