#!/bin/bash
em="$1"
lh=`echo $em | cut -f1 -d'@'`
rh=`echo $em | cut -f2 -d'@'`
if [ -z "$lh" -o -z "$rh" ]; then
  echo " Error: Bad email format $em"
  exit 0
fi

#da="@64.6.64.6"
da="@8.8.8.8"

hs=`echo -n $lh | openssl dgst -sha256 | cut -f2 -d' ' | cut -c1-56`
echo "-t type53 $hs._smimecert.$rh."
dig $da +short -t type53 $hs._smimecert.$rh. | grep -v ^";" | grep -v ^"$hs" | while [ "1" ]; do
    read a b c d
    if [ $? -ne 0 ]; then exit 1; fi

    rs1=`echo $a$b | grep ^10`
    rs2=`echo $a$b | grep ^20`
    rs3=`echo $a$b | grep ^30`
    rs5=`echo $a$b | grep ^50`

    if [ "$rs1" ]; then
	echo "*** End Entity + Validate ***"
	#danehdr="010000" 
	echo $d | xxd -r -p - | openssl x509 -inform der -text
    elif [ "$rs3" ]; then
	echo "*** End Entity + Optional Validate ***"
	#danehdr="030000"
	echo $d | xxd -r -p - | openssl x509 -inform der -text
    elif [ "$rs2" ]; then
	echo "*** Intermiediate ***"
	echo $d | xxd -r -p - | openssl x509 -inform der -text
    elif [ "$rs5" ]; then
        echo "*** PKCS7 ***"
	echo $d | xxd -r -p - | openssl cms -inform der -cmsout -print
    else 
        echo "Unknown: $a $b $c"
	continue
    fi
done
