#!/bin/bash

INPUT_FILE="domains.txt"
OUTPUT_FILE="certs.html"
BOT_TOKEN="6702352380:AAEfcIiEi3_kjAIqkpf95xpfjnOSlgGGyo8" # Replace with your actual bot token
TELEGRAM_USER_ID="158024537" # Replace with your actual Telegram user ID
NOW=$(date '+%Y-%m-%d %H:%M')

# Initialize an empty array to store domain data
# Each element will be: "diff_days|class|display_domain|enddate_val"
declare -a DOMAIN_DATA_ARRAY

send_alert() {
  local domain_full_input="$1" # The original input from domains.txt
  local msg="⚠️ Your domain '$domain_full_input' is about to expire in less than 5 days. Please renew it immediately to avoid service disruption."
  curl -s -X POST "https://api.telegram.org/bot$BOT_TOKEN/sendMessage" \
    -d chat_id="$TELEGRAM_USER_ID" \
    -d text="$msg"
}

# --- Data Collection Phase ---
while read -r line; do
  [[ -z "$line" ]] && continue

  domain_full_input="$line" # Store the original line for alerts
  display_domain=""         # This will be the domain displayed in HTML
  connect_domain=""         # This is the domain used for openssl connection
  port=""

  # Determine if it's a full URL or just a domain
  if [[ "$line" =~ ^https?:// ]]; then
    # Extract host and port for openssl connection
    host_port_path="${line#*://}"
    host_port="${host_port_path%%/*}"

    if [[ "$host_port" =~ :([0-9]+)$ ]]; then
      connect_domain="${host_port%:*}"
      port="${BASH_REMATCH[1]}"
    else
      connect_domain="$host_port"
      port="443" # Default HTTPS port
    fi

    # Extract only the domain name for display (remove www. and subdomains, keep main domain)
    # This is a simplified approach, adjust regex if needed for more complex cases
    display_domain=$(echo "$connect_domain" | sed -E 's/^(www\.)?([^/:]+)(:.*)?/\2/')
    # Fallback if sed fails or is too complex for some cases
    if [[ -z "$display_domain" ]]; then
        display_domain="$connect_domain"
    fi

  else # It's a plain domain or domain:port
    connect_domain="$line"
    port="443" # Default HTTPS port
    
    if [[ "$connect_domain" =~ :([0-9]+)$ ]]; then
      display_domain="${connect_domain%:*}" # Remove port from display
      port="${BASH_REMATCH[1]}"
    else
      display_domain="$connect_domain"
    fi
    # Clean display_domain for plain domains too
    display_domain=$(echo "$display_domain" | sed -E 's/^(www\.)?([^/:]+)(:.*)?/\2/')
    if [[ -z "$display_domain" ]]; then
        display_domain="$connect_domain"
    fi
  fi

  enddate=$(openssl s_client -connect "$connect_domain:$port" -servername "$connect_domain" </dev/null 2>/dev/null | openssl x509 -noout -enddate 2>/dev/null)

  if [[ $? -ne 0 || -z "$enddate" ]]; then
    DOMAIN_DATA_ARRAY+=("999999999|error|$display_domain|خطا")
    continue
  fi

  enddate_val=${enddate#notAfter=}
  end_ts=$(date -d "$enddate_val" +%s)
  now_ts=$(date +%s)
  diff_days=$(( (end_ts - now_ts) / 86400 ))

  class=""
  if (( diff_days <= 5 )); then
    class="red"
    send_alert "$domain_full_input" # Send Telegram alert with original input
  elif (( diff_days <= 15 )); then
    class="yellow"
  else
    class="green"
  fi

  DOMAIN_DATA_ARRAY+=("$diff_days|$class|$display_domain|$enddate_val")

done < "$INPUT_FILE"

# --- HTML Generation Phase ---
echo "<!DOCTYPE html>
<html lang='fa'>
<head>
<meta charset='UTF-8'>
<title>گزارش SSL</title>
<style>
  body { font-family: sans-serif; direction: rtl; background: #f5f5f5; padding: 20px; }
  table { width: 100%; border-collapse: collapse; background: white; }
  th, td { padding: 12px; border: 1px solid #ccc; text-align: center; }
  thead { background: #4caf50; color: white; }
  .green { background: #c8e6c9; color: #1b5e20; }
  .yellow { background: #fff9c4; color: #f57f17; }
  .red { background: #ffcdd2; color: #b71c1c; }
  .error { background: #ffebee; color: #d32f2f; font-style: italic; }
</style>
</head>
<body>
<h2>وضعیت SSL دامنه‌ها</h2>
<div class=\"timestamp\">آخرین به‌روزرسانی: $NOW</div>
<br> </br>
<table>
<thead><tr><th>دامنه</th><th>تاریخ انقضا</th><th>روز باقی‌مانده</th></tr></thead>
<tbody>" > "$OUTPUT_FILE"

# Sort the array numerically based on the first field (diff_days)
IFS=$'\n' sorted_data=($(sort -t'|' -k1,1n <<<"${DOMAIN_DATA_ARRAY[*]}"))
unset IFS

for entry in "${sorted_data[@]}"; do
  IFS='|' read -r diff_days class display_domain enddate_val <<< "$entry"
  unset IFS

  display_diff_days="$diff_days"
  if [[ "$diff_days" == "999999999" ]]; then
    display_diff_days="-"
  fi

  echo "<tr class=\"$class\"><td>$display_domain</td><td>$enddate_val</td><td>$display_diff_days</td></tr>" >> "$OUTPUT_FILE"
done

echo "</tbody></table></body></html>" >> "$OUTPUT_FILE"

echo "✅ فایل HTML ساخته شد و هشدارها برای دامنه‌های خطرناک ارسال شد."
