#!/bin/sh /etc/rc.common
# Copyright (C) 2016 Aleksander Morgado <aleksander@aleksander.es>

USE_PROCD=1
# Start right after network instead of S70: ModemManager needs 60s+ on small
# boards to acquire DBus and probe USB modems, and at S70 that work is starved
# by the S90 init block, delaying cellular WANs (and thus internet) by ~40-60s.
# Starting early overlaps the probing with the rest of the boot sequence; the
# wrapper waits for the DBus system bus, which we kick below since dbus itself
# is only at S60.
START=21

LOG_LEVEL="INFO"

start_service() {
	# Setup ModemManager service
	#
	# We will make sure that the rundir always exists, and we initially cleanup
	# all interfaces flagging them as unavailable.
	#
	# The cached events processing will wait for MM to be available in DBus
	# and will make sure all ports are re-notified to ModemManager every time
	# it starts.
	#
	# All these commands need to be executed on every MM start, even after
	# procd-triggered respawns, which is why this is wrapped in a startup
	# wrapper script called '/usr/sbin/ModemManager-wrapper'.
	#
	. /usr/share/ModemManager/modemmanager.common
	# dbus is enabled at S60; kick it now so ModemManager can register early.
	# When S60dbus runs later, procd sees the same running instance and no-ops.
	[ -x /etc/init.d/dbus ] && ! /etc/init.d/dbus running && /etc/init.d/dbus start >/dev/null 2>&1
	procd_open_instance "service"
	procd_set_param command /usr/sbin/ModemManager-wrapper
	procd_append_param command --log-level="$LOG_LEVEL"
	[ "$LOG_LEVEL" = "DEBUG" ] && procd_append_param command --debug
	[ "$LOG_LEVEL" = "DEBUG" ] && procd_append_param command --log-file "/var/log/mm.log"
	procd_set_param respawn "${respawn_threshold:-3600}" "${respawn_timeout:-5}" "${respawn_retry:-5}"
	procd_set_param pidfile "${MODEMMANAGER_PID_FILE}"
	procd_close_instance
	procd_open_instance "monitor"
	procd_set_param command /usr/sbin/ModemManager-monitor
	procd_set_param respawn "${respawn_threshold:-3600}" "${respawn_timeout:-5}" "${respawn_retry:-5}"
	procd_close_instance
}
