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

set -e

up() {
	echo "Starting MTP responder"
	if [ -d "/run/systemd" ]; 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 and usb-moded need
	# 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"
	systemctl stop umtprd
}

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

