#!/bin/bash

set -euxo pipefail

TEST_CONFIG=${TEST_CONFIG:-./test-config.sh}
. "$TEST_CONFIG"

get_expire_date() {
    local cert=${1:?No certificate supplied}

    ${OPENSSL} x509 -noout -enddate -in "${cert}" | awk -F= '{print $2}'
}

is_ca_cert() {
    local cert=${1:?No certificate supplied}
    local ca

    ca=$(${OPENSSL} x509 -noout -ext basicConstraints -in "${cert}" | \
        awk -F: '$1 ~ /^[[:space:]]*CA$/ {print $2}')
    [ "$ca" = TRUE ]
}

check_expiration() {
    local cert=${1:?No certificate supplied}
    local seconds=${2:?No minimum expiration seconds supplied}

    ${OPENSSL} x509 -noout -checkend "${seconds}" -in "${cert}" >/dev/null
}

# First count how many certs there are
total_certs=${#ALL_X509_CERTS[@]}
echo "1..${total_certs}"

# All CA certs should expire no less than 5 years from now
min_ca_expire_seconds=$((60 * 60 * 24 * 365 * 5))

# All non-CA certs should expire no less than 1 year from now
min_nonca_expire_seconds=$((60 * 60 * 24 * 365 * 1))

# Find the expiration for each cert in the keyring and make sure it's
# greater than the minimum time.
for cert in "${ALL_X509_CERTS[@]}"; do
    cert_basename=${cert##*/}
    expire_date=$(get_expire_date "${srcdir}/${cert}")
    case "${cert_basename}" in
        code-ev-*.crt)
            # GlobalSign EV code signing certificate. This is only valid
            # for 1 year, so warn when less than 30 days to expiration.
            min_expire_seconds=$((60 * 60 * 24 * 30))
            ;;
        *)
            if is_ca_cert "${srcdir}/${cert}"; then
                min_expire_seconds=${min_ca_expire_seconds}
            else
                min_expire_seconds=${min_nonca_expire_seconds}
            fi
            ;;
    esac

    # Compare to the minimum expiration date
    if check_expiration "${srcdir}/${cert}" "${min_expire_seconds}"; then
        echo "ok ${cert} expires ${expire_date}"
    else
        echo "not ok ${cert} expires ${expire_date}"
    fi
done
