#!/bin/sh
# clawbox-gparted-engine postinst: owner, directories, enable and (re)start the engine.
set -e

UNIT=clawbox-gparted-engine.service
OWNER_FILE=/etc/clawbox-gparted/owner

case "$1" in
	configure)
		# The installing user (sudo dpkg -i ...) owns the socket group and the vdisks.
		if [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != root ] && getent passwd "$SUDO_USER" >/dev/null; then
			printf '%s\n' "$SUDO_USER" > "$OWNER_FILE"
			chmod 0644 "$OWNER_FILE"
		elif [ ! -s "$OWNER_FILE" ]; then
			echo "clawbox-gparted-engine: SUDO_USER is not set; write the owner's user name to $OWNER_FILE" >&2
			echo "clawbox-gparted-engine: and run: systemctl restart $UNIT" >&2
		fi
		install -d -m 0750 /var/log/clawbox-gparted
		install -d -m 0755 /var/lib/clawbox-gparted
		install -d -m 0700 /var/lib/clawbox-gparted/vdisks
		install -d -m 0755 /var/lib/clawbox-gparted/mnt
		if [ -d /run/systemd/system ]; then
			systemctl daemon-reload || true
			systemctl enable "$UNIT" || true
			systemctl restart "$UNIT" || echo "clawbox-gparted-engine: $UNIT did not start; see journalctl -u $UNIT" >&2
		fi
		;;
esac

exit 0
