#!/bin/sh
# watchsync -- watch directory and rsync changes to remote
set -eu

if [ -z "${1:-}" ] || [ -z "${2:-}" ]; then
    echo "Usage: watchsync <local-dir> <remote:path>" >&2
    echo "Requires: fswatch or inotifywait" >&2
    exit 1
fi

local="$1"
remote="$2"

exclude=""
[ -f "$local/.gitignore" ] && exclude="--exclude-from=$local/.gitignore"
[ -d "$local/.git" ] && exclude="$exclude --exclude .git"

sync_cmd="rsync -iru --size-only $exclude --delete \"$local/\" \"$remote/\""

echo "[*] Watching $local -> $remote"
eval "$sync_cmd"

if command -v fswatch >/dev/null 2>&1; then
    fswatch -o "$local" | while read -r _; do
        echo "[$(date +%H:%M:%S)] syncing..."
        eval "$sync_cmd"
    done
elif command -v inotifywait >/dev/null 2>&1; then
    while inotifywait -r -e modify,create,delete "$local" >/dev/null 2>&1; do
        echo "[$(date +%H:%M:%S)] syncing..."
        eval "$sync_cmd"
    done
else
    echo "Install fswatch or inotifywait for live watching" >&2
    exit 1
fi
