#!/usr/bin/env bash

[ -z "${BASH_VERSION:-}" ] && { echo "Please run with bash"; exit 1; }

set -u
set -o pipefail

if [[ $# -ne 3 ]]; then
    echo "Usage: $0 server_hostname server_ip /path/to/domainsfile"
    exit 1
fi

server_hostname="$1"
server_ip="$2"
domains_file="$3"

if [[ ! -f "$domains_file" ]]; then
    echo "Domains file not found: $domains_file"
    exit 1
fi

if ! command -v curl >/dev/null 2>&1; then
    echo "curl is required but not installed."
    exit 1
fi

if ! command -v jq >/dev/null 2>&1; then
    echo "jq is required but not installed."
    exit 1
fi

sanitize_name() {
    printf '%s' "$1" | sed 's/[^A-Za-z0-9._-]/-/g'
}

safe_hostname="$(sanitize_name "$server_hostname")"
safe_ip="$(sanitize_name "$server_ip")"

get_next_output_file() {
    local n=1
    local candidate

    while :; do
        candidate="${safe_hostname}-${safe_ip}-domains-check-${n}.json"
        if [[ ! -e "$candidate" ]]; then
            echo "$candidate"
            return
        fi
        ((n++))
    done
}

get_title() {
    sed -n 's:.*<title[^>]*>\(.*\)</title>.*:\1:ip' | head -n1
}

fetch_domain() {
    local domain="$1"
    local response=""

    response=$(curl -L -s -k \
        --connect-timeout 15 \
        --max-time 45 \
        --resolve "${domain}:80:${server_ip}" \
        --resolve "${domain}:443:${server_ip}" \
        -w "\nHTTPSTATUS:%{http_code}\nFINALURL:%{url_effective}" \
        "http://${domain}" 2>/dev/null)

    printf '%s' "$response"
}

process_domain() {
    local domain="$1"
    local response body status final_url title

    echo "Processing: $domain" >&2

    response="$(fetch_domain "$domain")"

    body=$(printf '%s\n' "$response" | sed '/HTTPSTATUS:/,$d')
    status=$(printf '%s\n' "$response" | awk -F: '/^HTTPSTATUS:/ {print $2}')
    final_url=$(printf '%s\n' "$response" | sed -n 's/^FINALURL://p')
    title=$(printf '%s\n' "$body" | get_title)

    jq -n \
        --arg domain "$domain" \
        --arg status "${status:-0}" \
        --arg final_url "$final_url" \
        --arg title "$title" \
        '{
            domain: $domain,
            status: ($status | tonumber),
            final_url: $final_url,
            title: $title
        }'
}

outfile="$(get_next_output_file)"

tmpfile="$(mktemp)" || exit 1
trap '[[ -n "${tmpfile:-}" && -f "${tmpfile:-}" ]] && rm -f "$tmpfile"' EXIT

while IFS= read -r domain || [[ -n "$domain" ]]; do
    domain="${domain#"${domain%%[![:space:]]*}"}"
    domain="${domain%"${domain##*[![:space:]]}"}"

    [[ -z "$domain" ]] && continue
    [[ "$domain" =~ ^# ]] && continue

    process_domain "$domain" >> "$tmpfile"
done < "$domains_file"

jq -s '.' "$tmpfile" > "$outfile"

echo "Saved JSON results to: $outfile"
