#!/bin/sh
# /usr/bin/igworker of the .deb and .rpm packages. It runs the binary the service runs
# (/var/lib/igworker/bin/igworker, which updates itself), as the service user igworker and with
# the service's environment, so enroll, status, pause and resume see the service's credentials and
# state:
#
#   sudo igworker enroll https://<coordinator> <code>
#   sudo igworker status
#
# For any other user, tray, --version, --selftest and --licenses read nothing of the service's and
# run as the caller (the desktop autostart entry starts "igworker tray" in each desktop session).
# shellcheck disable=SC2086 # $env below is split into its NAME=value words on purpose
set -eu

user=igworker
bin=/var/lib/igworker/bin/igworker
[ -x "$bin" ] || bin=/usr/lib/igworker/igworker

# igworker.env holds NAME=value lines without spaces.
env=$(grep -v '^#' /usr/lib/igworker/igworker.env)
# The binary in /var/lib/igworker/bin belongs to the service user: root never runs it as root.
if [ "$(id -u)" -eq 0 ]; then
	exec runuser -u "$user" -- env $env "$bin" "$@"
fi
case "${1:-}" in
tray | -version | --version | -selftest | --selftest | -licenses | --licenses | -h | -help | --help | "")
	exec "$bin" "$@"
	;;
esac
if [ "$(id -un)" = "$user" ]; then
	exec env $env "$bin" "$@"
elif command -v sudo >/dev/null 2>&1; then
	exec sudo -u "$user" -- env $env "$bin" "$@"
fi
echo "igworker: run this with sudo: it uses the service's credentials" >&2
exit 1
