#!/bin/zsh

[[ -z $1 ]] && { echo "where to get the cert?" >&2; exit 1; }

PORT=${2:-443}

fetch() {
    if [[ $1 == "-" ]]
    then
        cat
    elif [[ -f $1 ]]
    then
        fetch_file $1
    else
        fetch_remote $1
    fi
}

fetch_remote() {
    : | openssl s_client -connect $1:${PORT} 2>/dev/null| awk '/BEGIN CERTIFICATE/,/END CERTIFICATE/'
}

fetch_file() {
    cat $1
}

coproc openssl x509 -in /dev/stdin -noout -subject -issuer -startdate -enddate -ext subjectAltName | sed '/X509v3 Subject Alternative Name/ {n ; s/DNS://g ; s/, /\n    /g;}'

fetch $1 >&p

exec 3> >(LC_ALL=C sort)

sort=0
while read -t 0.5 -p line
do
    if [[ $line = notBefore=* ]]
    then
        date -d ${line#notBefore=} '+Since: %d.%m.%Y %T'
        continue
    elif [[ $line = notAfter=* ]]
    then
        date -d ${line#notAfter=} '+Until: %d.%m.%Y %T'
        continue
    fi


    if (( sort == 1 ))
    then
        echo "   $line" >&3
    else
        [[ $line = 'X509v3 Subject Alternative Name:' ]] && sort=1
        echo $line
    fi
done
