#!/bin/bash -e
# vim:syntax=sh
#
# Copyright (c) 2010,2013 SUSE Linux Products GmbH
# Copyright (c) 2020 SUSE LLC
# Author: Ludwig Nussel
#
# update /etc/ssl/certs for compatibility with legacy applications
# 
# 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.
#

[ -d "$statedir" ]
etccertsdir="/etc/ssl/certs"
pemdir="$statedir/pem"

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

mkdir -p "$pemdir"
trust extract --purpose=server-auth --filter=ca-anchors --format=pem-directory-hash -f "$pemdir"

# fix up /etc/ssl/certs if it's not a link pointing to /var/lib/ca-certificates/pem
if ! [ -L "$etccertsdir" -a "`readlink $etccertsdir`" = "$pemdir" ]; then
    echo "Warning: $etccertsdir needs to be a link to $pemdir, fixing" >&2
    if [ -d "$etccertsdir" ]; then
	mv -Tv --backup=numbered "$etccertsdir" "$etccertsdir.old"
    fi
    ln -Tsv --backup=numbered "$pemdir" "$etccertsdir"
fi
