#!/bin/bash

srcdir=/app/global/
dstmodule=simba
excludedir=/root/
rsyncuser=root
rsyncpassdir=/app/config/rsync/passwd.txt

source /opt/lnxall_app/share/libubox/jshn.sh

json_load_file() {
    json_load "$(cat /app/config/stactrl_mqtt.json)"
    json_get_var host_t 'host'
    dstip=$host_t
}

rsync_file_loop() {
    inotifywait -m $srcdir -e close_write,modify,delete,create,attrib,move | while read path action file
    do
        echo "File '$file' has been $action"
        /opt/lnxall_app/bin/rsync -avH --port=873 $srcdir rsync://$rsyncuser@$dstip/$dstmodule --password-file=/app/cert/rsync_passwd
    done
}

main() {
    json_load_file
    if [ "${dstip}" = "" ]; then
        echo "No IP address found"
        exit 1
    fi
    case $1 in
        loop)
            rsync_file_loop
            ;;
        single)
            echo "Manual file synchronization"
            /opt/lnxall_app/bin/rsync -avH --port=873 $srcdir rsync://$rsyncuser@$dstip/$dstmodule --password-file=/app/cert/rsync_passwd
            ;;
        *)
            echo "Usage: $0 {loop|single}"
            exit 1
            ;;
    esac
}

main "$@"
