Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

aoe2de-set-cert-from-server.sh (Source)

#!/bin/sh
IPADDRESS="${IPADDRESS:-${1}}"
if test -z "${INFILE}" ;
then
    scriptdir="$( dirname "$( readlink -f "${0}" )" )"
    INFILE="$( find "${scriptdir}" "${scriptdir}/.." "${scriptdir}/../.." -ipath '*/certificates/cacert.pem' -print -quit )"
fi
INFILE="$( readlink -f "${INFILE}" )"
if test -z "${IPADDRESS}" ;
then
    echo "Fatal! Provide \$1 or IPADDRESS (IP address or hostname) to fetch certificate. Aborted." 1>&2
    exit 1
fi
cert="$( </dev/null openssl s_client -connect "${IPADDRESS}:443" 2>/dev/null | openssl x509 -in /dev/stdin )"
# Exit if the connection failed. Openssl x509 already printed an error, so do not print another.
if test -z "${cert}" ; then exit 1 ; fi
next_next_to_last="$( echo "${cert}" | awk '{a[NR]=$0} END {print a[NR-2]}' )"
if ! grep -q -e "${next_next_to_last}" "${INFILE}" ;
then
    echo "You need the cert! File ${INFILE} does not have the cert."
    if test -n "${APPLY}" ;
    then
        echo "Applying the the cert." 1>&2
        echo "${cert}" >> "${INFILE}"
    else
        echo "Dry run only! Please run with APPLY=1 to add the cert."
    fi
else
    echo "File ${INFILE} has the cert already."
fi