#!/bin/bash
# Bash script to query DDNS service for hostname current IP address and create or update UFW firewall rules
# to allow access to all ports and protocols from the dynamic IP address.
# This script is intended to be run from a cron job with root privileges.
# The script will only update the firewall rules if the IP address has changed.

# Set the DDNS service URL
DDNS_HOSTNAME="akanealw.com"
# Get the DDNS hostname IP address
DDNS_IP=$(dig +short ${DDNS_HOSTNAME})
# Get the current IP allowed in UFW for this hostname
OLD_IP=$(/usr/sbin/ufw status | grep $DDNS_HOSTNAME | head -n1 | tr -s ' ' | cut -f3 -d ' ')

# Check if the DDNS hostname IP address is valid
if [[ "${DDNS_IP}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  # Check if the old IP is valid
  if [[ "${OLD_IP}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    # Check if the DDNS service IP address is different from the old IP address
    if [[ "${DDNS_IP}" != "${OLD_IP}" ]]; then
        # Delete the old rule
        /usr/sbin/ufw delete allow from $OLD_IP to any
        # Create a new rule for the new IP address
        /usr/sbin/ufw allow from "${DDNS_IP}" to any comment $DDNS_HOSTNAME
    else
      echo "$0: The IP address is the same, no need to update the firewall rules."
    fi
  else
    # Create a new rule for the new IP address
    /usr/sbin/ufw allow from "${DDNS_IP}" to any comment $DDNS_HOSTNAME
  fi
else
  echo "$0: DDNS IP address is not valid for ${DDNS_HOSTNAME}: ${DDNS_IP}"
fi
