#!/bin/bash
input="web_list.json"
output="web_check.json"
tmpfile=$(mktemp)

jq -c '.[]' "$input" | while read -r entry; do
    host=$(echo "$entry" | jq -r '.host')
    domain=$(echo "$entry" | jq -r '.domain')
    path=$(echo "$entry" | jq -r '.path')
    word=$(echo "$entry" | jq -r '.["word-to-check"]')
    basic_auth=$(echo "$entry" | jq -r '.basic_auth')
    user=$(echo "$entry" | jq -r '.basic_auth_name // empty')
    pass=$(echo "$entry" | jq -r '.basic_auth_pass // empty')

    [[ -z "$path" ]] && path="/"

    # --- SSL check ---
    ssl_info=$(echo | openssl s_client -servername "$domain" -connect "$domain:443" 2>/dev/null | openssl x509 -noout -dates -issuer)
    ssl_released=$(echo "$ssl_info" | grep 'notBefore' | cut -d= -f2)
    ssl_expiry=$(echo "$ssl_info" | grep 'notAfter' | cut -d= -f2)
    ssl_company=$(echo "$ssl_info" | grep 'issuer' | sed -n 's/.*O=\([^,]*\).*/\1/p')
    ssl_ok=0
    if [[ $(date -d "$ssl_expiry" +%s) -gt $(date +%s) ]]; then ssl_ok=1; fi

    # --- Content check ---
    url="https://$domain$path"
    if [[ "$basic_auth" == "true" ]]; then
        content=$(curl -s -u "$user:$pass" "$url")
    else
        content=$(curl -s "$url")
    fi
    word_ok=0
    [[ "$content" == *"$word"* ]] && word_ok=1

    # --- Scrivi in tmp JSON ---
    jq -n \
      --arg host "$host" \
      --arg domain "$domain" \
      --arg path "$path" \
      --arg word "$word" \
      --argjson wordcheck_ok "$word_ok" \
      --argjson sslcheck_ok "$ssl_ok" \
      --arg ssl_released "$ssl_released" \
      --arg ssl_expiry "$ssl_expiry" \
      --arg ssl_company "$ssl_company" \
      '{
        host: $host,
        domain: $domain,
        path: $path,
        wordtocheck: $word,
        wordcheck_ok: $wordcheck_ok,
        sslcheck_ok: $sslcheck_ok,
        "ssl-released": $ssl_released,
        "ssl-expiry": $ssl_expiry,
        "ssl-company": $ssl_company
      }' >> "$tmpfile"
done

# --- Combina in array JSON ---
jq -s '.' "$tmpfile" > "$output"
rm "$tmpfile"

echo "Check completato. Output salvato in $output"
