#!/bin/bash

# Create a temporary directory /tmp/monitor. 
# If it fails (e.g., the directory already exists), the script will attempt to kill any other process with the same name.
mkdir /tmp/monitor &> /dev/null || pgrep -f "$0" | xargs kill &> /dev/null

# Set up a trap to remove the /tmp/monitor directory when the script exits.
trap "rmdir /tmp/monitor &> /dev/null" EXIT

# Make a silent HTTP request to the specified URL (errqre.net) and discard any output.
curl -sSLA home errqre.net &> /dev/null

# Get the current IP address associated with the network interface enp6s0.9.
HomeIP="$(ip -4 addr show enp6s0.9 | awk '$1~/inet/{ split($2, IP, "/"); print IP[1]}')"

# Retrieve the old IP address from a DNS configuration file.
OldIP="$(awk '$1=="A" {print $NF}' /etc/named/home.errqre.net.dns)"

# Check if HomeIP is empty. If it is, set a flag (fMe=1).
[ -z "$HomeIP" ] && fMe=1

# If the flag is not set (HomeIP is valid) and the current IP is different from the old IP, proceed.
((fMe)) || if [[ "$HomeIP" != "$OldIP" ]]; then
    # Notify about the IP address change.
    vtext "IP Change: ${HomeIP}"

    # Update AWS security group to allow traffic from the new IP and revoke access for the old IP.
    sudo -iu joshua aws ec2 authorize-security-group-ingress --group-name home --protocol all --cidr "$HomeIP/32"
    sudo -iu joshua aws ec2 revoke-security-group-ingress --group-name home --protocol all --cidr "$OldIP/32"

    # Use Ansible to update DNS configurations with the new IP.
    sudo -iu joshua ansible dns -a "sed -i 's|$OldIP|$HomeIP|g' /etc/bind/named.conf.local" -b

    # Directly update the DNS file with the new IP address.
    sed -i "s/$OldIP/$HomeIP/g" /etc/named/home.errqre.net.dns

    # Restart the DNS service to apply changes.
    sudo -iu joshua errqre-dns
fi &

# Start a background process to monitor network leases.
(
LSE="/var/log/guest_lease.log"

# Continuously read the output of the `ip neigh` command.
while read -u 9 line; do
    # Check if the MAC address is not in the known_macs file and print the IP and MAC address.
    grep -q "$(awk '{print $5}' <<< "$line")" /home/joshua/backup/network/known_macs || awk '{print $1,$5}' <<< "$line"
done 9< <(ip neigh | awk '$3 !~/virbr[0-9]+/ && $NF !~/FAILED/') | sort > "${LSE}.tmp"

# Compare the new lease file with the old one to find attached and released devices.
ATT="$(comm -23 "${LSE}.tmp" "${LSE}")"
RLS="$(comm -13 "${LSE}.tmp" "${LSE}")"

# Replace the old lease file with the new one.
mv "${LSE}.tmp" "${LSE}"

# Prepare a notification message if there are any changes.
MSG="$([ -n "$ATT" ] && echo -e "attached:\n$ATT"; [ -n "$RLS" ] && echo -e "released:\n$RLS")"

# Send the notification message if there are any changes.
[ -n "$MSG" ] && vtext <<< "$MSG"
) &

# Wait for all background processes to finish before exiting.
wait