#!/bin/bash
# Copyright (c) 2019 Algo Communication Products Ltd.

# update-ca-certificates creates links from *.crt files in
# /usr/local/share/ca-certificates to /etc/ssl/certs
ALGO_CERT_DIR=/usr/local/share/ca-certificates/algo-trusted
USER_CERT_DIR=/opt/algo/config/certs/trusted
UPDATE_CERTS=0
mkdir -p $ALGO_CERT_DIR

# Remove any dead symlinks if certs were removed from user directory
# Use while loop to handle files with spaces and output errors to /dev/null
while read i; do
	if [ -L "$i" ]; then
		rm "$i";
		UPDATE_CERTS=1
	fi
done <<< "$(find $ALGO_CERT_DIR -xtype l 2>/dev/null)"

# Create links from certs with various extensions in user directory to .crt
# extension in system directory
cd $USER_CERT_DIR
while read i; do
	if [ ! -L $ALGO_CERT_DIR/"$i".crt ] && [ -f "$i" ] ; then
		ln -sf "$USER_CERT_DIR/$i" "$ALGO_CERT_DIR/$i.crt"
		UPDATE_CERTS=1
	fi
done <<< "$(find * \( -name '*.pem' -o -name '*.cer' -o -name '*.crt' \) 2>/dev/null)"

if [ $UPDATE_CERTS -eq 1 ]; then
	update-ca-certificates -f
fi
