summaryrefslogtreecommitdiff
path: root/.config/login.d/02_xdg_runtime_dir.sh
blob: 6d93359a801dfe03fa2b81a5c1c36c5225bc962e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# This should be readable by /bin/sh

# Set XDG_RUNTIME_DIR if we can
if [ -z "$XDG_RUNTIME_DIR" ] && shopt -q login_shell && type flock &>/dev/null; then
	_diy_xdg_runtime_login() {
		export XDG_RUNTIME_DIR="$XDG_CACHE_HOME/xdg-runtime-dir/$HOSTNAME"
		# There's a race condition here, between the `ln -s` and `flock`.
		# But it's not like I'll be hammering a box with logins.
		if [ ! -d "$XDG_RUNTIME_DIR" ]; then
			local tmp="$(mktemp -d --tmpdir -- "${USER}@${HOSTNAME}-runtime.XXXXXXXXXX")"
			mkdir -p -- "$XDG_CACHE_HOME/xdg-runtime-dir"
			ln -sfT -- "$tmp" "$XDG_RUNTIME_DIR"
		fi
		if ! [ /dev/fd/7 -ef "$XDG_CACHE_HOME/xdg-runtime-dir/.lock" ]; then
			exec 7>"$XDG_CACHE_HOME/xdg-runtime-dir/.lock"
			if flock -sn 7; then
				# Unfortunately this doesn't survive across exec(1).
				trap _diy_xdg_runtime_logout EXIT
			fi
		fi
	}
	_diy_xdg_runtime_logout() {
		if flock -xn 7; then
			rm -rf -- "$(readlink "$XDG_RUNTIME_DIR")"
		fi
	}
	_diy_xdg_runtime_login
fi