#!/usr/bin/env bash

brt_ssl() {
  local host="${1:-}"
  local port="${2:-443}"

  if [[ -z "$host" ]]; then
    brt_error "Usage: brt -ssl <host> [port]"
    exit 1
  fi

  host="${host#https://}"
  host="${host#http://}"
  host="${host%%/*}"
  if [[ "$host" == *:* ]]; then
    port="${host##*:}"
    host="${host%%:*}"
  fi

  brt_require openssl
  brt_info "SSL certificate for ${host}:${port}"

  local cert
  cert=$(echo | openssl s_client -connect "${host}:${port}" -servername "$host" 2>/dev/null \
    | openssl x509 -noout -subject -issuer -dates -fingerprint -sha256 2>/dev/null) || {
    brt_error "Could not retrieve certificate for ${host}:${port}"
    exit 1
  }

  echo "$cert"

  local expiry
  expiry=$(echo | openssl s_client -connect "${host}:${port}" -servername "$host" 2>/dev/null \
    | openssl x509 -noout -enddate 2>/dev/null | cut -d= -f2)

  if [[ -n "$expiry" ]]; then
    local exp_epoch now days
    exp_epoch=$(date -j -f "%b %d %T %Y %Z" "$expiry" +%s 2>/dev/null || date -d "$expiry" +%s 2>/dev/null)
    now=$(date +%s)
    days=$(( (exp_epoch - now) / 86400 ))
    if (( days < 0 )); then
      brt_error "Certificate expired ${days#-} days ago"
    elif (( days < 30 )); then
      brt_warn "Certificate expires in ${days} days"
    else
      brt_ok "Certificate valid for ${days} more days"
    fi
  fi
}
