#!/bin/dash
# Description: Multiplex USB connections to Apple devices (imobiledevice)
#
# Copyright (C) step 2023
# License: GNU GPL Version 3 or later

### configuration

### routines

start() {
	is_up && stop

	if ! is_up; then
		/usr/sbin/usbmuxd --udev --user usbmux
		is_up && echo "usbmuxd started"
	fi
}

stop() {
	if is_up; then
		mountp="$(mounts)"
		if [ -n "$mountp" ]; then
			printf "usbmuxd still running due to active mountpoints:\n%s\n" "$mountp"
			return 1
		else
			# gently first
			if is_up; then
				usbmuxd --exit
				sleep 1
			fi
		fi
	fi

	if is_up; then
		killall -q usbmuxd
		sleep 1
	fi

	if is_up; then
		killall -q -9 usbmuxd
	fi

	stop_imd_monitor

	is_up || echo "usbmuxd stopped"
}

stop_imd_monitor() {
# started by /etc/udev/rules.d/55-fatdog-usbmuxd.rules
	killall -q fatdog-imd-monitor.sh
	sleep 1
	killall -q -9 fatdog-imd-monitor.sh
}

mounts() {
	awk '$3=="fuse.ifuse" {print $2}' < /proc/mounts
}

is_up() {
	pidof usbmuxd > /dev/null
}

### main
case "$1" in
	start)          start ;;
	stop)           stop  ;;
	restart|reload) start ;;
	status)         is_up &&
		echo "usbmuxd is running" ||
		echo "usbmuxd is stopped" ;;
	status_is_up)  is_up ;;
	mounts)         mounts;;
esac
