#!/bin/bash
# Description       : Script to verify if provided hostnames point to the local server
# This will generate an output which can be used in the Let's Encrypt config file

# User input
read -p "Enter space-separated hostnames to verify: " -a HOSTNAMES

# Check if at least one hostname is provided
if [ -z "$HOSTNAMES" ]; then
    echo "Usage: hostname1 [hostname2 ...]"
    exit 1
fi

# Display IP of the server
serverIP=$(hostname -I | awk '{print $1}')
echo "Server IP: $serverIP"
echo "-----------------------------"

matchingHostnames=""

# Loop through all arguments
for HOST in "${HOSTNAMES[@]}"; do
    echo "Checking $HOST..."

    #resolvedIP=$(dig a +short "$HOST")
    mapfile -t resolvedIP < <(dig a +short "$HOST")

    # Check if result is empty
    if [ -z "$resolvedIP" ]; then
        echo "Cannot resolve $HOST"
    else
	# Check if multiple results are returned, meaning CNAME records can be used
	if [ "${#resolvedIP[@]}" -gt 1 ]; then
	    echo "Resolved IP: ${resolvedIP[@]}"
	    echo "Multiple results are returned, please check all DNS records of this domain"
	else
            echo "Resolved IP: $resolvedIP"

	    # Check if IPs are the same
            if [ $serverIP = $resolvedIP ]; then
               	echo "Match"
	        matchingHostnames+="${HOST} "
            else
               	echo "Mismatch between server IP $serverIP and resolved IP $resolvedIP, please check where $HOST is pointing to"
	    fi
        fi
    fi
    echo "-----------------------------"
done

# Show matching results
if [ -n "$matchingHostnames" ]; then
    echo "This is the list of matching hostnames, please replace this with the current line in /etc/dehydrated/domains.txt"
    echo "Make sure to double check the initial domain name, they need to be the same. If they're different, a new certificate will be created in a different folder and you need to replace the certificate name in the vhost"
    echo "Result:"
    echo "$matchingHostnames"
else
    echo "No matching hostnames can be found"
fi
