#!/bin/sh

. /lib/functions.sh
. /usr/lib/configsync_lib.sh

my_logger() {
   logger -t configsync_event_delay "${@}"
}


DELAY=$(uci_get ${MY_SERVICE_NAME} global eventdelay 30)
my_logger "  copy system configuration to configsync  received parameters: $@  delay = $DELAY"

# add service to servicelist if not in list
for SERVICE in "$@"; do
    add_to_list $CS_SERVICELIST ${SERVICE}
done

sleep $DELAY

SERVICELIST=$(cat $CS_SERVICELIST)
SERVICE_ENABLE=$(uci_get ${MY_SERVICE_NAME} global enabled 0)
if [ ${SERVICE_ENABLE} -eq 1 ]; then
    my_logger "start synchronization"
    RETVAL=1
    for CHANGED_FILE in ${SERVICELIST}; do
        my_logger  "Handle ${CHANGED_FILE} SYSTEM-TO-CONFIGSYNC"
        if /usr/bin/${MY_SERVICE_NAME}_handler.sh SYSTEM-TO-CONFIGSYNC "${CHANGED_FILE}"; then
            RETVAL=0
        fi
        update_md5sum ${CHANGED_FILE}
    done
    if [ $RETVAL -eq 0 ]; then
#        /usr/bin/${MY_SERVICE_NAME}_handler.sh APPLY
        my_logger  "Apply configsync changes"
        killall -USR1 p1905
    fi
    my_logger "end synchronization"
else
    my_logger "${MY_SERVICE_NAME} service not running -> trigger ignored"
fi
>$CS_SERVICELIST

