#!/usr/bin/env bash

# Function to show help text
show_help() {
  cat <<EOF
Usage: $0 <URL>

Fetches and prints the leaf SSL certificate from the given URL.

Arguments:
  <URL>        The domain name or IP address of the server (without https://)
               Example: github.com

Options:
  --help       Show this help message and exit

Examples:
  $0 example.com
EOF
}

# Handle --help
if [[ $1 == "--help" || $1 == "-h" ]]; then
  show_help
  exit 0
fi

# Check if URL argument is provided
if [ -z "$1" ]; then
  echo "Error: No URL provided."
  echo "Try '$0 --help' for usage."
  exit 1
fi

url="$1"

# Get and print the leaf certificate. Uses </dev/null to get openssl to work non-interactively
cert_chain=$(openssl s_client -showcerts -connect "$url:443" </dev/null 2>/dev/null | openssl x509 2>/dev/null)

if [[ -z $cert_chain ]]; then
  echo "❌ Failed to retrieve certificate for $url"
  exit 1
fi

echo "$cert_chain"
