#!/bin/sh

usage() {
    echo "Usage: indicator-network-daemon-debug start|stop"
    exit 1
}

connman() {
    if [ -x /etc/init.d/connman ]; then
	    /etc/init.d/connman $1
    fi
}

ofono() {
    if [ -x /etc/init.d/ofono ]; then
	    /etc/init.d/ofono $1
    fi
}

run() {
    cmd=$1; shift
    args=$@

    if [ -x $cmd ]; then
	$cmd $args
    fi
}

start() {
    connman stop
    ofono stop
    killall -q wpa_supplicant

    sleep 3

    # just to be sure
    killall -q connmand ofonod wpa_supplicant

    run /sbin/wpa_supplicant -B -u -s -ddd
    export OFONO_AT_DEBUG=1
    run /usr/sbin/ofonod -d
    run /usr/sbin/connmand -d
}

stop() {
    # just to be sure
    killall -q connmand ofonod wpa_supplicant

    sleep 3

    # just to be sure
    killall -q connmand ofonod wpa_supplicant

    ofono start
    connman start

    # wpasupplicant is started with dbus activation
}

if [ "$#" != 1 ]; then
    usage
fi

if [ `id -u` != 0 ]; then
    echo "Must be root."
    exit 3
fi

case $1 in
    start)
	start
	;;
    stop)
	stop
	;;
    *)
	echo "Invalid commmand"
	usage
	exit 2
	;;
esac
