#!/bin/sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DESC="iNet wireless daemon"

DAEMON=/usr/libexec/iwd

PIDFILE="/run/iwd.pid"
SSD_OPTIONS="--oknodo --quiet --exec $DAEMON --pidfile $PIDFILE"

test -f $DAEMON || exit 0

test -f /etc/default/rcS && . /etc/default/rcS

RCMAIN=/usr/share/resources/default/init/main
[ -f "$RCMAIN" ] && . "$RCMAIN"

if [ "$rc_has_wlan" != "yes" -a "$1" != "stop" ]; then
    echo "Not starting $DESC, disabled via resources"
    exit 0
fi

set -e

case $1 in
  start)
	echo -n "Starting $DESC: "
	start-stop-daemon --start --background --make-pidfile $SSD_OPTIONS -- --syslog
	# wait for iwd to finish initializing
	sleep 1
	if [ -e /sys/class/ieee80211/phy0 ]; then
	        ready=
		for i in 1 2 3 4 5 6 7 8 9; do
	                iwctl device wlan0 show > /dev/null 2> /dev/null && ready=1 && break
	                sleep 1
	        done
	        [ -n "$ready" ] || iwctl device wlan0 show > /dev/null 2> /dev/null || echo -n 'wlan0 does not come up! '
	fi
	echo "${DAEMON##*/}."
  ;;
  stop)
	echo -n "Stopping $DESC: "
	start-stop-daemon --stop $SSD_OPTIONS && rm -f $PIDFILE
	echo "${DAEMON##*/}."
  ;;
  restart|force-reload)
	$0 stop
	sleep 1
	$0 start
  ;;
  status)
	pidof ${DAEMON} >/dev/null
	status=$?
        if [ $status -eq 0 ]; then
                echo "$DESC is running."
        else
                echo "$DESC is not running"
        fi
        exit $status
   ;;
   *)
	N=/etc/init.d/iwd
	echo "Usage: $N {start|stop|restart|force-reload|status}" >&2
	exit 1
	;;
esac

exit 0
