#!/bin/sh
# Read-only helper: inspect the public certificate and enforce an expiry window.
set -eu

if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
  echo "usage: $0 HOST [DAYS]" >&2
  exit 2
fi

host=$1
days=${2:-30}
case "$days" in
  ''|*[!0-9]*)
    echo "DAYS must be a non-negative integer" >&2
    exit 2
    ;;
esac

certificate=$(mktemp "${TMPDIR:-/tmp}/xbcatm-cert.XXXXXX")
trap 'rm -f "$certificate"' EXIT HUP INT TERM

openssl s_client -connect "$host:443" -servername "$host" </dev/null 2>/dev/null \
  | openssl x509 -out "$certificate"

openssl x509 -in "$certificate" -noout -subject -issuer -dates -fingerprint -sha256

seconds=$((days * 86400))
if openssl x509 -in "$certificate" -checkend "$seconds" -noout >/dev/null; then
  echo "certificate remains valid for at least ${days} day(s)"
else
  echo "certificate expires within ${days} day(s)" >&2
  exit 1
fi
