#!/bin/sh
# Enable/disable MTP USB mode by delegating FunctionFS operations to uMTP-responder
#
# Copyright (c) Dylan Van Assche (2026)
TIMEOUT=10s

up() {
	echo "Starting MTP responder"
	if [ -x "/usr/bin/systemctl" ]; then
		systemctl start umtprd
	elif [ -f "/etc/rc.conf" ]; then
		rc-service umtprd start
	else
		echo "Unsupported init system"
		exit 1
	fi

	# Wait up to 10s for EP fds to appear
	# usb-signaller needs to wait for the
	# FunctionFS daemon to prepare the gadget
	# before activating it
	timeout $TIMEOUT sh -c 'while [ $(ls /dev/mtp/ep* | wc -l) -le '1' ]; do sleep 1; done'
}

down() {
	echo "Stopping MTP responder"
	if [ -x "/usr/bin/systemctl" ]; then
		systemctl stop umtprd
	elif [ -f "/etc/rc.conf" ]; then
		rc-service umtprd stop
	else
		echo "Unsupported init system"
		exit 1
	fi
}

case $1 in
    up)
        up
        ;;
    down)
        down
        ;;
    *)
        echo "need an argument (up|down)"
        exit 0
        ;;
esac

