#!/bin/bash
# 
# sdu.sh : Serial DNS Updater for bind
# Version: 2.0 (stable for use in Production)
# Author: Christophe Casalegno / Brain 0verride
# Website: https://scalarx.com
# Twitter: https://twitter.com/ScalarTech
# Email: christophe.casalegno@scalarx.com
# Note: N/A

tmpdir="/tmp"
backupdir="/backupdns"
dirlock="/var/run"
datename=$(date +"%d-%m-%y-%T")
zonefile=$1

SCRIPTNAME=$(basename "$0")

# First verification, process already launched ?

export LOCKSYNC="$dirlock/$SCRIPTNAME.lock"
PID=$$
echo "[$(date +"%Y/%m/%d %H:%M:%S")] Trying to launch script $0"

if [ -f "$LOCKSYNC" ]
        then
                echo "Wait : lockfile $LOCKSYNC is present. we must verify..."
                PIDLOCK=$(cat "$LOCKSYNC")
                if [ -f /proc/"$PIDLOCK"/exe ]

                        then

                                echo "The process is currently running. Launching $SCRIPTNAME aborted."
                                exit
                        
                        else

                                echo "The process doesn't seems currently running anymore. Lauching $SCRIPTNAME"...
                                rm "$LOCKSYNC"
                fi
fi

echo "Lockingfile creation... " "$LOCKSYNC"
echo "$PID" > "$LOCKSYNC"

# Second verification : backupdir exist ? 

if [ -r "$backupdir" ]

        then

                echo "The backup directory already exist : it's cool, don't worry"
                echo "Processing..."

        else
        
                echo "The backup directory doesn't exist : Creating backup directory..."
	       mkdir $backupdir
	       fixdate=$datename
	       mkdir $backupdir/"$fixdate"

fi



cat "$zonefile" > "$backupdir"/"$fixdate"/"$zonefile"
gawk 'BEGIN{ser=strftime("%Y%m%d",systime() )*100} /[0-9]{9,10}/{sub($1,$1 < ser ? ser : $1+1)}1' "$zonefile" > $tmpdir/"$zonefile".tmp
cat $tmpdir/"$zonefile".tmp > "$zonefile"
rm $tmpdir/"$zonefile".tmp




