#!/bin/bash

if [ $# -eq 0 ]; then
    echo "Fly Launcher: usage: $0 <start|restart|stop>"
    exit 1
fi

if [ "$EUID" -ne 0 ]; then
    echo "Run as a root please"
    exit 2
fi


CONNMAN=`which connmand`
OFONO=`which ofonod`
HUAWEI=`which huawei-audio`
SENSOR=`which iio-sensor-proxy`

if [ $1 == 'start' ]; then
    /etc/init.d/wicd stop

    if ! pgrep --full $SENSOR > /dev/null; then
        echo "Fly Launcher: starting iio-sensor-proxy"
        $SENSOR &
    fi

    if ! pgrep --full $CONNMAN > /dev/null; then
        echo "Fly Launcher: starting connman"
        $CONNMAN
    fi

    if ! pgrep --full $OFONO > /dev/null; then
        echo "Fly Launcher: starting ofono"
        $OFONO
    fi

    if ! pgrep --full $HUAWEI > /dev/null; then
        echo "Fly Launcher: starting huawei-audio"
        $HUAWEI &
    fi
elif [ $1 == 'restart' ]; then
    echo "Fly Launcher: ofono restart"
    pkill --full $OFONO
    #sleep ?
    $OFONO
elif [ $1 == 'stop' ]; then
    echo "Fly Launcher: stopping connman"
    /etc/init.d/wicd start
    pkill --full $CONNMAN
else
    echo "Fly Launcher: Unknown argument! Usage: $0 <start|restart|stop>"
    exit 3
fi

exit
