#!/usr/bin/env bash
# Quick TLS configuration checker for a target host.
# Usage: bash scripts/tls_check.sh example.com [port]
set -euo pipefail

HOST="${1:?Usage: $0 <host> [port]}"
PORT="${2:-443}"

echo "=== TLS Check: $HOST:$PORT ==="
echo ""

echo "--- Certificate Info ---"
echo | openssl s_client -connect "$HOST:$PORT" -servername "$HOST" 2>/dev/null | openssl x509 -noout -subject -issuer -dates -fingerprint 2>/dev/null

echo ""
echo "--- Protocol Support ---"
for proto in tls1 tls1_1 tls1_2 tls1_3; do
  result=$(echo | openssl s_client -connect "$HOST:$PORT" -servername "$HOST" -"$proto" 2>&1)
  if echo "$result" | grep -q "BEGIN CERTIFICATE"; then
    case $proto in
      tls1|tls1_1) echo "  ⚠️  $proto: SUPPORTED (should be disabled)" ;;
      tls1_2) echo "  ✅ $proto: SUPPORTED" ;;
      tls1_3) echo "  ✅ $proto: SUPPORTED (best)" ;;
    esac
  else
    case $proto in
      tls1|tls1_1) echo "  ✅ $proto: DISABLED (good)" ;;
      *) echo "  ℹ️  $proto: NOT SUPPORTED" ;;
    esac
  fi
done

echo ""
echo "--- Certificate 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
  EXPIRY_EPOCH=$(date -d "$EXPIRY" +%s 2>/dev/null || date -jf "%b %d %T %Y %Z" "$EXPIRY" +%s 2>/dev/null || echo 0)
  NOW_EPOCH=$(date +%s)
  DAYS_LEFT=$(( (EXPIRY_EPOCH - NOW_EPOCH) / 86400 ))
  if [ "$DAYS_LEFT" -lt 0 ]; then
    echo "  🔴 EXPIRED $((DAYS_LEFT * -1)) days ago!"
  elif [ "$DAYS_LEFT" -lt 30 ]; then
    echo "  ⚠️  Expires in $DAYS_LEFT days"
  else
    echo "  ✅ Expires in $DAYS_LEFT days ($EXPIRY)"
  fi
fi

echo ""
echo "--- HSTS Header ---"
HSTS=$(curl -sI "https://$HOST" 2>/dev/null | grep -i strict-transport-security || echo "")
if [ -n "$HSTS" ]; then
  echo "  ✅ $HSTS"
else
  echo "  ⚠️  No HSTS header found"
fi
