#!/bin/bash
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance with the License. A copy of the
# License is located at
#
#	http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
#
# this script searches through known locations for certs (borrowed from 
# https://go.dev/src/crypto/x509/root_linux.go) and writes them to the
# current dir 

set -ex

ROOT=$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )
cd "${ROOT}/misc/certs"

# Possible certificate files
certFiles=("/etc/ssl/certs/ca-certificates.crt" "/etc/pki/tls/certs/ca-bundle.crt" "/etc/ssl/ca-bundle.pem" "/etc/pki/tls/cacert.pem" "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem" "/etc/ssl/cert.pem")

# search and stop once certs are found
thisCertFile=""
for file in ${certFiles[@]}; do
  if test -f $file; then
    thisCertFile=$file
    break
  fi
done

# if we found a cert file, we'll copy else return 0
if [ ! -z "$thisCertFile" ]
then
  cp $thisCertFile ./host-certs.crt
else
  exit 1
fi