#!/bin/sh -e
#
# ---
# source: https://github.com/no-gravity/certdays

case $(uname) in
  Darwin) gnudate="gdate" ;;
  *) gnudate="date" ;;
esac

certdate=$(
  echo \
    | openssl s_client -servername "$1" -connect "$1":443 2>/dev/null \
    | openssl x509 -noout -dates \
    | tail -n 1 \
    | cut -d= -f2
)
certsec=$(${gnudate} +%s -d "${certdate}")
nowsec=$(${gnudate} +%s)
# shellcheck disable=SC2116
days=$(echo "$(((certsec - nowsec) / (60 * 60 * 24)))")

echo "$1: ${days}"

if [ -z "$2" ]; then
  echo "done"
  exit 0
fi

printf '%s' "Lasts longer then $2 days? "

if ( (${days} >"$2")); then
  echo "Yes."
else
  echo "NO!!!!!!!!!!!!!!"
  exit 1
fi
