#!/bin/bash

# script courtesy of @lbergey on PIAF Forum

dt=$(date)
# Make a Temp file to use as a Global Variable
ck=$(mktemp)
cd /root
# Set Global Variable to "N" for trigger a iptables-restart
echo "N" > $ck
# process all .iptables files in /root
ls -1 /root/*.iptables | while read line
do
echo "account: $line"
# extract fqdn and ip address from the .iptables file
fqdn=`cat ${line} | cut -f 1 -d " "`
ip=`cat ${line} | cut -f 2 -d " "`
# Only process records where the ip address is not equal to fqdn and
# ip and fqdn are not empty
if [ "$fqdn" != "$ip" ] && [[ -n "${ip// }" ]] && [[ -n "${fqdn// }" ]]; then
# Get the current IP for the fqdn
test=`dig +short $fqdn`
LEN=${#test}
if [ $LEN -gt 15 ]; then
echo "Ooops. We gotta a DIG overage problem. Forcing a match on IP to avoid disaster."
test=$ip
fi
if [ $LEN -lt 7 ]; then
echo "Ooops. We gotta a DIG fail problem. Forcing a match on IP to avoid disaster."
test=$ip
fi
if [ "$ip" != "$test" ]; then
echo "Account ${line} CHANGED"
echo "$dt" >> /var/log/ipchecker.log
echo "Account ${line} CHANGED" >> /var/log/ipchecker.log
# Set the iptables-restart flag to Yes
echo "Y" > $ck
echo " FQDN: $fqdn"
echo "OLD IP: $ip"
echo "NEW IP: $test"
echo " FQDN: $fqdn" >> /var/log/ipchecker.log
echo "OLD IP: $ip" >> /var/log/ipchecker.log
echo "NEW IP: $test" >> /var/log/ipchecker.log
echo "$fqdn $test" > ${line}
fi
fi
done 
# Retreive the iptables-restart flag
restartflag=$(cat $ck)
# Remove the Temp File
rm -f $ck
if [ "$restartflag" == "Y" ]; then
echo "iptables-restart"
echo "iptables-restart" >> /var/log/ipchecker.log
/usr/local/sbin/iptables-restart
fi
exit 0
#eof

