#!/bin/sh
# Samba "dfree command" for Sharestead storage limits. Samba runs it as the
# connected user, in the share's folder, and reads "total free" in KiB.
# In the user's personal folder with a folder limit, that limit is shown;
# in a share with a limit, the share's limit. Free space is never more than
# the disk really has. If this script fails, Samba reports the disk's
# own values.
#
# The disk is read through /proc/self/cwd: Samba runs this without the
# share's "force group", so the user may lack the right to look up "." in a
# share folder (mode 0770), while the jump through /proc needs no lookup.
set -eu
set -- $(stat -f -c '%b %a %S' /proc/self/cwd)
total=$(( $1 * $3 / 1024 ))
free=$(( $2 * $3 / 1024 ))
dir=/run/sharestead/dfree/$(id -u)
cwd=$(readlink /proc/self/cwd)
limit=""
# <uid>.home: "total free path" of the personal folder
if [ -r "$dir.home" ] && read -r htotal hfree hpath < "$dir.home"; then
	case "$cwd/" in "$hpath"/*) limit="$htotal $hfree" ;; esac
fi
# share-*: "total free path" of a share with a limit
if [ -z "$limit" ]; then
	for f in /run/sharestead/dfree/share-*; do
		[ -r "$f" ] && read -r stotal sfree spath < "$f" || continue
		case "$cwd/" in "$spath"/*) limit="$stotal $sfree"; break ;; esac
	done
fi
if [ -n "$limit" ]; then
	set -- $limit
	total=$1
	if [ "$2" -lt "$free" ]; then
		free=$2
	fi
fi
echo "$total $free"
