#!/bin/bash
# systemd.generator(7)
set -e
set -f
set -u

# exit if disabled explicitly
if grep -q tabletmode=0 /proc/cmdline
	then exit 0
fi

# $PWD is added for local tests
if ! TABLET_AUTODETECT_ONLY=1 PATH="$PWD:/usr/libexec/tablet-rotation:$PATH" tablet-autodetect.sh
	# exit if no tablet has been detected
	then exit 0
fi

# XXX Do we really need this logic in finding systemd unit?
# What if we make a symlink to /lib/systemd/system/touchegg.service,
# but /etc/systemd/system/touchegg.service exists, will
# systemd use the unit file from /lib or from /etc?
unit=
for i in \
	/etc/systemd/system \
	/run/systemd/system \
	/usr/lib/systemd/system \
	/lib/systemd/system
do
	if test -f "$i"/touchegg.service; then
		unit="$i"/touchegg.service
	fi
done
[ -n "$unit" ] || exit 0
# enable touchegg if we are a tablet
# touchegg emulates right button click by clicking on screen with 2 fingers
late="$3"
mkdir -p "$3"/multi-user.target.wants
ln -s "$unit" "$3"/multi-user.target.wants/touchegg.service

# an indicator for using in /etc/xdg/autostart/*.desktop (e.g. to start onboard)
echo "# created by tablet-rotation systemd.generator(7)" > /run/tablet-mode-enabled
