description "MTP protocol server"

start on :sys:android-usb-connected or android-usb-connected or :sys:android-mtp-on or android-mtp-on or started unity8
stop on :sys:android-usb-disconnected or android-usb-disconnected or :sys:android-mtp-off or android-mtp-off or desktop-end

pre-start script
    [ "$USER" != "lightdm" ] || { stop; exit 0; }

    test -e /sys/devices/virtual/android_usb/android0/state || { stop; exit 0; }
    sleep 0.5 # avoid race condition where "state" isn't updated yet and causes mtp-server to not launch
    grep -q DISCONNECTED /sys/devices/virtual/android_usb/android0/state && { stop; exit 0; }
    test -e /sys/kernel/config/usb_gadget/g1/configs/c.1/mtp.gs0 || { stop; exit 0; }

    # Fix for bug LP: #1389223: UnityGreeter isn't available immediately
    if ! dbus-send --session --print-reply \
            --dest=com.canonical.UnityGreeter \
            / org.freedesktop.DBus.Introspectable.Introspect 2>&1 | \
                grep -qc IsActive; then
        sleep 10
    fi
end script

env GOOGLE_LOGTOSTDERR=1

respawn
respawn limit unlimited

exec /usr/bin/mtp-server
