To fix ownership of a directory in /var/syncthing/, a cronjob find script

2022-02-18

I use Syncthing to synchronize a directory of files between my workstations. On OpenBSD the Syncthing daemon is by default ran as user _syncthing and I decided to go with that as more secure.

The issue arose when a directory I very frequently use from my user account was originally owned by user _syncthing group _syncthing. Recursively changing ownership of the whole directory resulted in Syncthing not being able to modify files sometimes. And when Syncthing added synchronized files to the directory, they lacked permissions for the user account.

I can't find how this can be solved in Syncthing and while I know I could try monitoring the files, for now I decided to write a crude cronjob.

Now, I understand that the crontab(1) utility is for editing only the spool per-user crontabs and the systemwide /etc/crontab is ok to be edited manually.

So I made my crontab

*/3 * * * * _syncthing -ns /etc/the_syncthing_script.sh

to run every 3rd minute, as user syncthing, sending me mail on a non-zero exit code, the bash script that I decided to place in /etc, /etc/the_syncthing_script.sh:

#!/usr/bin/env bash
case `whoami` in
	_syncthing)
		PREOWN=
		FINALOWN=
		;;
	mf)
		PREOWN="doas chown mf"
		FINALOWN=:
		;;
	root)
		PREOWN=
		FINALOWN=
		;;
	*)
		>&2 echo "bad user $(whoami)"
		exit 1
		;;
esac

# find everything in Biezace owned by _syncthing
# chown to group syncthing
# chown to us if needed for chmod
# chmod g+w
# if directory, chmod ug+x
# chown to mf if not already
# stderr all failures

ECHO="-exec echo"

find /var/syncthing/Biezace \
-user _syncthing \
\( \
-exec ${PREOWN:=chown }:_syncthing {} \+ -o \
	$ECHO 1 {} \; \) \
\( \
-exec chmod g+w {} \+ -o \
	$ECHO 2 {} \; \) \
\( \(	\(	-type d \
		-exec chmod ug+x {} \+ -o \
			$ECHO 3 {} \; \
	\) \
	-or \
	-exec : \; \
\) -o \
	$ECHO 4 {} \; \) \
\( \
-exec ${FINALOWN:=chown mf \{\}} \; -o \
	$ECHO 5 {} \; \) \
| ifne -n false  # moreutils; so cron -n sends fail email


/gemlog/