#!/usr/bin/env bash

if [ -z "$1" ] || [ -z "$2" ]; then
    echo "Usage: $0 <subdomain> <access_token>"
    exit 1
fi

SUBDOMAIN=$1
ACCESS_TOKEN=$2
API_URL="https://www.n4no.org/api/getpostlink?subdomain=$SUBDOMAIN"
BOT_USER="@dns@m.n4no.org" 

DOMAIN_N4NO="$SUBDOMAIN.n4no.org" 

echo -n "Finding my external IP..."
IPV4=$(curl -s "https://n4no.org/api/getmyip")
IPV6=""           

echo " Found: $IPV4"

echo -n "Checking DNS records for $DOMAIN_N4NO..."


if [ "$DNS_IPV4" == "$IPV4" ]; then
  echo "GOOD :-)"
  echo "$DOMAIN_N4NO already points to $IPV4. Exiting."
  exit 0
else
  echo "MISMATCH"
  echo " $DOMAIN_N4NO does NOT point to $IPV4. It points to $DNS_IPV4 instead."
  echo "We will request an update..."
fi



# multiline with escaped \n
BODY=$(printf "%s\\\n" "$BOT_USER" "$DOMAIN_N4NO" "$IPV4" "$IPV6")

echo "Body content is: $BODY"

echo -n "Fetching post link ..."

POST_LINK=$(curl -s "$API_URL")
echo " Found: $POST_LINK"

if [[ $POST_LINK == https://* ]]; then
    echo -n  "Updating post for [ $DOMAIN_N4NO ] ... "

    # MASTODON API, update post
    RESPONSE=$(curl -s -X PUT "$POST_LINK" \
        -H "Authorization: Bearer $ACCESS_TOKEN" \
        -H "Content-Type: application/json" \
        -d "{\"status\":\"$BODY\"}")
    
    if [[ $RESPONSE == *"\"id\":"* ]]; then
        echo "Post updated successfully!"
	echo "Waiting 10 seconds for notifications to be parsed and DNS UPDATE.." 

	for i in {1..10}; do
    		printf "====="
    		sleep 1
	done
	echo 


	echo "-----------------------------------------"


	FIRST_A_RECORD=$(dig @ns1.n4no.org A $DOMAIN_N4NO +short | head -n 1)
	FIRST_AAAA_RECORD=$(dig @ns1.n4no.org AAAA $DOMAIN_N4NO +short | head -n 1)

	if [[ "$FIRST_A_RECORD" == "$IPV4" ]]; then
		echo "GOOD!"
    		echo "√√√ A record match: $FIRST_A_RECORD equals $IPV4"
	else
		echo "MISMATCH :-("
    		echo "~~~ A record mismatch: $FIRST_A_RECORD does not equal $IPV4"
	fi

	if [[ "$FIRST_AAAA_RECORD" == "$IPV6" ]]; then
   	 	echo "√√√ AAAA record match: [$FIRST_AAAA_RECORD] equals [$IPV6]"
	else
    		echo "~~~ AAAA record mismatch: [$FIRST_AAAA_RECORD] does not equal [$IPV6]"
	fi

	echo
	echo "-----------------------------------------"

    else

	echo
	echo "-----------------------------------------"
        echo "### Failed to update post."
	echo "Response: $RESPONSE"
    fi


else
    echo 
    echo "-----------------------------------------"
    echo "### Failed to fetch the post link. Response: $POST_LINK"
fi

