#!/bin/bash
#
# update-ca-certificates
#
# Copyright (c) 2010,2013 SUSE Linux Products GmbH
# Copyright (c) 2020,2021 SUSE LLC
# 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=
fresh=

export statedir

help_and_exit()
{
    cat <<-EOF
	USAGE: $0 [OPTIONS]
	OPTIIONS:
	  --verbose, -v     verbose output
	  --fresh, -f       start from scratch
	  --help, -h        this screen
EOF
    exit 0
}

case "$1" in
    -v|--verbose) verbose='-v'; shift ;;
    -f|--fresh) fresh='-f'; shift ;;
    -h|--help) help_and_exit ;;
    -*) echo "invalid option: $1" >&2; exit 1 ;;
esac

# set sane umask
umask 0222;

case "${TRANSACTIONAL_UPDATE,,*}" in
    true|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

mkdir -p "$statedir"
# serialize calls if we can
if [ -z "$_CA_CERTIFICATES_LOCKED" -a -x /usr/bin/flock ]; then
    export _CA_CERTIFICATES_LOCKED="1"
    exec /usr/bin/flock "$statedir" "$0" "$@"
    echo "failed to lock $statedir\n" >&2
    exit 1
fi

while read s f; do
    if [ -L "$f" -a "`readlink "$f"`" = "/dev/null" ]; then
	[ -z "$verbose" ] || echo "skipping $f"
	continue
    else
	[ -z "$verbose" ] || echo "running $f .."
    fi
    "$f" $fresh $verbose
done < <(find "$hooksdir1" "$hooksdir2" -maxdepth 1 \( -type f -o -type l \) -name '*.run' -printf '%f\t%p\n'|sort -k 1,1 -u)
