#!/bin/bash

#------------------------------------------------------------------
# Start the inotifywait in the host to monitor directories 
#
# April, 2016 Budhaditya Banerjee, Lokheshvar Balakumar
#
# Copyright (c) 2016-2017 by cisco Systems, Inc.
# All rights reserved.
#------------------------------------------------------------------

if [[ -f /etc/init.d/spirit_log.sh ]]; then 
    source /etc/init.d/spirit_log.sh
fi 

# Logical flow is to wait for events close_write,create and delete on the list
# on files and directories read from the file /etc/inotify/monitor and 
# output the name of the file that generated either of these events. 
# The output is then parsed through /etc/inotify/scripts to execute the 
# corresponding script

platform_log "Starting inotify to monitor directories/files to be syned between XR and host"

inotifywait -e close_write,create,delete -m -q -r --fromfile /etc/inotify/monitor --timefmt '%d %m %y %H:%M' --format '%w %f %e' | while read DIRECTORY FILENAME EVENT
do
    PARENTDIR=`dirname ${DIRECTORY}`
    while IFS=$':' read -r -a LINE; do
        if [ "${LINE[0]}" == "$DIRECTORY$FILENAME" ] 
        then
	    platform_log "Executing ${LINE[1]}"
            ${LINE[1]} ${DIRECTORY} ${FILENAME}
        elif [ "${LINE[0]}" == "$DIRECTORY" ]
        then
            platform_log "Executing ${LINE[1]}"
            ${LINE[1]} ${DIRECTORY} ${FILENAME}
        elif [ "${LINE[0]}" == "$PARENTDIR/" ]
        then
            platform_log "Executing ${LINE[1]}"
            ${LINE[1]} ${DIRECTORY} ${FILENAME}
        fi
    done < /etc/inotify/scripts
done

