#!/bin/dash 
# Description: Ensure $SPOT_HOME/Downloads always belongs to spot.
#

SPOT_HOME=$(awk -F: '$1=="spot" {print $6}' /etc/passwd)
CONFPATH="/etc/autochown.conf"
PIDFILE="/run/autochown.pid"
MAXWATCHES=32768

start_autochown() {
	# make sure we can actually chown files in Downloads
	touch $SPOT_HOME/Downloads/test-autochownd-99
	chown spot $SPOT_HOME/Downloads/test-autochownd-99
	if [ "$(ls -l $SPOT_HOME/Downloads/test-autochownd-99 | cut -d "/" -f 1 | grep spot)" = "" ] ; then
		echo "autochownd exiting"
		rm $SPOT_HOME/Downloads/test-autochownd-99
		exit
	fi
	rm $SPOT_HOME/Downloads/test-autochownd-99
	
	# make sure 1st line always contains the Downloads folder
	CMD="> spot:spot::$(realpath $SPOT_HOME/Downloads)"
	! [ -e $CONFPATH ] && echo "$CMD" > $CONFPATH
	grep -qF "$CMD" $CONFPATH || sed -i -e "1 s|^.*$|$CMD|" $CONFPATH
	
	# increase watch limit if needed
	read p < /proc/sys/fs/inotify/max_user_watches
	[ $p -lt $MAXWATCHES ] && echo $MAXWATCHES > /proc/sys/fs/inotify/max_user_watches
	
	# start the daemon
	# autochown -d -p $PIDFILE $CONFPATH
	while true; do # anti-crash loop, from SFR, will look for something better later
		autochown -p $PIDFILE $CONFPATH
		case $? in 137|143) break ;; esac # 137=Killed (kill -9), 143=Terminated (kill)
		sleep 1
	done &	
}

stop_autochown() {
	read pid < $PIDFILE
	kill $pid
	sleep 1
    kill -0 $pid 2>/dev/null && kill -9 $pid
    rm -f $PIDFILE
}

is_up_autochown() {
	test -e "$PIDFILE"
}

case $1 in
  start) 
	start_autochown 
	;;
	
  stop) 
	stop_autochown 
	;;
	
  restart)
    stop_autochown
    sleep 1
    start_autochown
    ;;

  status)
	is_up_autochown && echo "autochownd is running." || echo "autochownd is stopped."
    ;;
esac

