#!/usr/bin/bash
# set -xv

usage() {
    echo -e 'Usage: platsec-system-certs [silo]' 1>&2
    echo -e '\t where silo is either of prod, eng, alpaca_prod, alpaca_eng, alpaca_pdx, workday, aws, awsdev, il4, eu_sov, all' 1>&2
    echo -e '\t Example:' 1>&2
    echo -e '\t\t platsec-system-certs prod' 1>&2
    echo -e '\t\t platsec-system-certs il4' 1>&2
    echo -e '\t\t platsec-system-certs eu_sov' 1>&2
    exit 1
}


if [[ "$#" -ne 1 || ("$1" != "prod" && "$1" != "eng" && "$1" != "workday" && "$1" != "aws" && "$1" != "awsdev" && "$1" != "all" && "$1" != "alpaca_eng" && "$1" != "alpaca_pdx" && "$1" != "alpaca_prod" && "$1" != "il4" && "$1" != "eu_sov") ]]; then
    usage
fi

# Injecting a configuration to redirect stdout and stderr to log file in /etc/platsec/logs
echo "### Initializing platsec-system-certs, check out the logs in /etc/platsec/logs/platsec-system-certs"
source /etc/platsec/conf/platsec-logs-vars platsec-system-certs

# Setup host
SILO=$1
if [[ $SILO == "aws" ]]; then
    SILO="prod"
fi

if [[ $SILO == "awsdev" ]]; then
    SILO="eng"
fi

if [[ $SILO == "alpaca_eng" ]]; then
    # alpaca_eng is for jssecacerts. Continue to install eng certs
    SILO="eng"
fi

if [[ $SILO == "alpaca_pdx" ]]; then
    # alpaca_pdx is for jssecacerts. Continue to install eng certs -- This is for backward compatibility
    SILO="eng"
fi

if [[ $SILO == "alpaca_prod" ]]; then
    # alpaca_prod is for jssecacerts. Continue to install prod certs
    SILO="prod"
fi

if [[ $SILO == "il4" ]]; then
    SILO="il4"
fi

if [[ $SILO == "eu_sov" ]]; then
    SILO="eu_sov"
fi

bash -x update-ca-trust force-enable

#### Add the found certs
if [[ $SILO == "all" ]]
then
    cp /etc/platsec/silos/eng/*.cer /etc/pki/ca-trust/source/anchors/ || true
    cp /etc/platsec/silos/prod/*.cer /etc/pki/ca-trust/source/anchors/ || true
else
    cp /etc/platsec/silos/$SILO/*.cer /etc/pki/ca-trust/source/anchors/ || true
fi
bash -x update-ca-trust extract
