#!/bin/sh
#
# certck - view details of a sites certificate

set -e

usage() {
  printf '%s' "\
Usage:
  $(basename "$0") host.domain[:PORT] (defaults to :443)

Options:
  [-h]       - Print help text.
  [-i]       - Verbose with '--insecure' to troubleshoot expired/bad certs.
  [-p]       - Print certificate of given host.
  [-r]       - Retrieve certificate of given host.
  [-x]       - Verbose output.
"
  exit 0
}

trap_error() {
  ret="$?"
  [ "${ret}" -eq 0 ] \
    || printf '%b\n' "\nERROR line ${1}: Command exited with status ${ret:?}"
}

if [ "$#" -eq 0 ]; then
  usage
fi

insecure=0
print=0
retrieve=0

while getopts ':hiprx' opt; do
  case "${opt}" in
    h) usage ;;
    i) insecure=1 ;;
    p) print=1 ;;
    r) retrieve=1 ;;
    x)
      PS4='[${LINENO}]+ '
      set -o xtrace
      trap 'trap_error ${LINENO}' HUP INT TERM EXIT
      ;;
    *)
      printf "%s: Unrecognized option: '-%c'\n" "${0##*/}" "${OPTARG}" >&2
      exit 1
      ;;
  esac
done
shift "$((OPTIND - 1))"

host="${1##https://}"
test -n "${host}" || exit 1
if [ "${host}" = "${host%:*}" ]; then
  host="${host}:443"
fi

if [ -n "${insecure}" ]; then
  # use --insecure so that we can troubleshoot expired / otherwise bad certs
  curl --verbose --insecure "https://${host}" 2>&1 1>/dev/null \
    | grep -E '(Connected to|subject:|date:|issuer)'
fi

if [ -n "${print}" ]; then
  echo \
    | openssl s_client -showcerts -servername "${host}" -connect "${host}" \
    | openssl x509 -inform pem -noout -text
fi

if [ -n "${retrieve}" ]; then
  echo \
    | openssl s_client -connect "${host}" 2>&1 \
    | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
  # echo | openssl s_client -connect $@:443 2>&1| sed '/BEGIN CERT/,/END CERT/p;d'
fi
