#!/bin/bash
# Copyright (C) 2025 Spearhead Systems SRL

set -euo pipefail

if [[ $# < 3 ]]; then
    echo "Usage:   ${@: 0:1} <domains> <crit date> <warn date>" 1>&2
    echo "Example: ${@: 0:1} google.com yahoo.com 2024-05-07 2024-05-21" 1>&2
    exit 1
fi

# Extract from args
domains="${@: 1:$#-2}"
warn="${@: -1:1}"
crit="${@: -2:1}"


# Attempt lookup of domain name expiration using whois.
#
# Unfortunately, there's no actual format for whois entries, so this is a
# best-effort based on things seen in the wild. Note that ccTLDs usually do not
# publish expiry dates at all.
whois_domain() {
    whois "$1" | grep 'Expir.*' | head -1 | grep -Eo '[0-9]{4}-[0-9]{2}-[0-9]{2}'
}

# Attempt lookup of domain name expiration using RDAP.
#
# Unfortunately, RDAP tools are still relatively new and not available in many
# repos, so we do the lookup manually using curl. There's a two-step process:
#
# * look up (and cache) dns info from IANA.
# * using the info from IANA, query the TLD for the domain
#
# Also, as of 2025, RDAP is useful with gTLDs and about 1/3rd of ccTLDs.
rdap_domain() {
    dns_file="/tmp/agent_domains_expiry.json"
    domain="$1"
    tld="${domain##*.}"   # get TLD off end of $domain

    # Only attempt to fetch the file if it's older than 24h (or doesn't exist)
    if [[ ! -f "$dns_file" ]] || [[ -n $(find "$dns_file" -mtime +0 2>/dev/null) ]]; then
      # We do an conditional GET, using the file's timestamp
      curl --silent \
           --time-cond "$dns_file" \
           --output "$dns_file"    \
           "https://data.iana.org/rdap/dns.json"
    fi
    registrar=$(jq -r '.services[] | select(.[0][] == "'"$tld"'") | .[1][0]' "$dns_file" 2> /dev/null)
    if [[ "$registrar" != "" ]]; then
        curl -s "${registrar}domain/${domain}" |
            jq -r '.events[] | select(.eventAction == "expiration") | .eventDate' 2> /dev/null |
            grep -Eo '[0-9]{4}-[0-9]{2}-[0-9]{2}'
    fi
}


echo "<<<domains_expiry:sep(0)>>>"

for domain in $domains; do
    expires=$(rdap_domain "$domain" || true)
    if [[ "$expires" == "" ]]; then
        expires=$(whois_domain "$domain" || true)
    fi

    echo -n "{\"domain\": \"$domain\", \"state\": \""

    if [[ "$expires" == "" ]]; then
        echo -n "UNKNOWN"
    elif [[ "$expires" < "$crit" ]]; then
        echo -n "CRIT"
    elif [[ "$expires" < "$warn" ]]; then
        echo -n "WARN"
    else
        echo -n "OK"
    fi

    if [[ "$expires" != "" ]]; then
        echo -n "\", \"expires\": \"$expires"
    fi
    echo "\"}"
done
