#!/bin/sh
# chkconfig: 2345 25 75
### BEGIN INIT INFO
# Provides:          iwd
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start iwd at boot time
# Description:       Enable service provided by iwd.
# X-Start-Before:
# X-Stop-After:
# X-Timesys-Start-Number:  26
# X-Timesys-Stop-Number:   74
### END INIT INFO

DAEMON=/usr/lib/iwd
CONFIG_FILE=/etc/iwd/main.conf
PID_DIR=/var/run/iwd
PID_FILE=$PID_DIR/pid

if [ -f /etc/default/iwd ] ; then
        . /etc/default/iwd
fi

start()
{
    echo -n "Starting iwd: "

    # Already running?
    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE" 2>/dev/null)

        if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
            echo "[already running]"
            return 0
        fi

        # Remove stale PID file
        rm -f "$PID_FILE"
    fi

    # Create PID directory
    mkdir -p "$PID_DIR" || {
        echo "[FAIL]"
        return 1
    }

    # Start iwd
    DBUS_SYSTEM_BUS_ADDRESS=unix:path=/run/dbus/system_bus_socket \
    "$DAEMON" &
    PID=$!

    # Save PID
    echo "$PID" > "$PID_FILE"

    # Give iwd a moment to start
    sleep 1

    # Verify that iwd is still running
    if kill -0 "$PID" 2>/dev/null; then
        echo "OK"
        return 0
    fi

    # iwd exited during startup
    rm -f "$PID_FILE"
    echo "[FAIL]"
    return 1
}

stop()
{
    if [ ! -f "$PID_FILE" ]; then
        echo "iwd is not running (pid file not found)"
        return 0
    fi

    PID=$(cat "$PID_FILE" 2>/dev/null)

    if [ -z "$PID" ]; then
        echo "Invalid PID file"
        rm -f "$PID_FILE"
        return 1
    fi

    # Check whether PID belongs to a running process
    if ! kill -0 "$PID" 2>/dev/null; then
        echo "iwd is not running"
        rm -f "$PID_FILE"
        return 0
    fi

    echo -n "Stopping iwd: "

    kill "$PID" 2>/dev/null

    # Wait for iwd to exit
    COUNT=0
    while kill -0 "$PID" 2>/dev/null; do
        sleep 1
        COUNT=$((COUNT + 1))

        if [ "$COUNT" -ge 5 ]; then
            echo "[FAIL]"
            return 1
        fi
    done

    rm -f "$PID_FILE"
    echo "[ OK ]"
    return 0
}

restart()
{
    stop
    sleep 1
    start
}

status()
{
    if [ ! -f "$PID_FILE" ]; then
        echo "iwd is not running"
        return 3
    fi

    PID=$(cat "$PID_FILE" 2>/dev/null)

    if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
        echo "iwd is running (PID $PID)"
        return 0
    fi

    echo "iwd is not running (stale pid file)"
    return 3
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac

exit $?
