nextcloud: Add nc-inotify-sync
[shutils.git] / nextcloud / nc-inotify-sync
diff --git a/nextcloud/nc-inotify-sync b/nextcloud/nc-inotify-sync
new file mode 100755 (executable)
index 0000000..e310352
--- /dev/null
@@ -0,0 +1,101 @@
+#!/bin/sh
+
+NCC=/usr/bin/nextcloudcmd
+if ! [ -x ${NCC} ]; then
+       echo "There is no ${NCC}."
+       exit 2
+fi
+
+IWAIT=/usr/bin/inotifywait
+if ! [ -x ${IWAIT} ]; then
+       echo "There is no ${IWAIT}."
+       exit 2
+fi
+
+usage() {
+       cat << EOF
+
+Calls nextcloudcmd to sync a source directory and server url. The script
+triggers a synchronization when (i) the source directory was changed or (ii)
+after some period, whatever happens first. The nextcloudcmd is called with
+netrc for login.
+
+Usage:
+ $0 [OPTIONS] source_dir server_url
+ $0 -h
+
+OPTIONS:
+  -h        Show this text
+  -o        One-shot instead of looping
+  -s        Silent, be less verbose
+  -t SECS   Sync period if nothing changed locally.
+            Default: 180
+
+EXAMPLE
+    $0 ~/.vimwiki https://cloud.example.com/remote.php/webdav/vimwiki
+EOF
+}
+
+NCC_OPTS="-n"
+IWAIT_OPTS=""
+
+SILENT=0
+ONESHOT=0
+PERIOD=180
+
+while getopts "host:" OPTION; do
+       case "${OPTION}" in
+               h)
+                       usage
+                       exit
+                       ;;
+               o)
+                       ONESHOT=1
+                       ;;
+               s)
+                       SILENT=1
+                       NCC_OPTS="${NCC_OPTS} -s"
+                       IWAIT_OPTS="${IWAIT_OPTS} -q"
+                       ;;
+               t)
+                       PERIOD=${OPTARG}
+                       ;;
+               *)
+                       usage
+                       exit 1
+                       ;;
+       esac
+done
+shift $((OPTIND-1))
+
+SOURCE_DIR=$1
+SERVER_URL=$2
+
+if [ -z "${SOURCE_DIR}" ] ; then
+       echo "No source directory given."
+       usage
+       exit 1
+fi
+
+if [ -z "${SERVER_URL}" ] ; then
+       echo "No server URL given."
+       usage
+       exit 1
+fi
+
+NCC_OPTS="${NCC_OPTS} ${SOURCE_DIR} ${SERVER_URL}"
+
+while true; do
+       echo "About to sync..."
+       sleep 2
+       [ "$SILENT" = "1" ] || echo "[$(date '+%F %X')] Perform sync..."
+
+       ${NCC} ${NCC_OPTS}
+
+       [ "${ONESHOT}" = "1" ] && break
+
+       sleep 3
+       [ "$SILENT" = "1" ] || echo ""
+       [ "$SILENT" = "1" ] || echo "[$(date '+%F %X')] Wait for ${PERIOD} secs or source directory change."
+       ${IWAIT} ${IWAIT_OPTS} -t ${PERIOD} -r -e modify -e move -e create -e delete ${SOURCE_DIR}
+done