#!/usr/bin/env bash

set -euo pipefail

usage() {
  echo "Usage: $0 --host-name <hostname>"
  exit 1
}

host=""

while [[ $# -gt 0 ]]; do
  case "$1" in
  --host-name)
    host="$2"
    shift 2
    ;;
  -h | --help)
    usage
    ;;
  *)
    echo "Unknown argument: $1"
    usage
    ;;
  esac
done

if [[ -z $host ]]; then
  echo "Error: --host-name is required"
  usage
fi

echo | openssl s_client -connect "${host}:443" -showcerts 2>/dev/null |
  awk '/-----BEGIN CERTIFICATE-----/,/-----END CERTIFICATE-----/{print; if(/-----END CERTIFICATE-----/) exit}' |
  openssl x509 -noout -dates -subject
