#! /bin/sh

# Script for controlling the PAN connection.
# Based on a PAN script by Frantisek Dufka.
# Adapted by Martin Grimme.

# This script is invoked by the pan-daemon when connecting or disconnecting
# from the PAN IAP.

# exit codes:
#   0: OK
#   1: you are not root
#   2: connection failed


# are we root?
if [ `id -u` != 0 ]; then
    echo "Only root may run $0."
    exit 1
fi


COMMAND=$1
USER=user

BTADDR=`su - $USER -c "gconftool-2 -g /system/osso/connectivity/BT/preferred"`
BTNAME=`su - $USER -c "gconftool-2 -g /system/bluetooth/device/${BTADDR}/name"`
if [ "x$BTNAME" = "x" ]; then
    BTNAME=phone
fi

PAN_ROLE=NAP

SYSTEM_BUS='unix:path=/tmp/system_bus_socket'
SESSION_BUS='unix:path=/tmp/session_bus_socket'




infoprint() {
    local msg=$1
    su - $USER -c "dbus-send --session --dest=org.freedesktop.Notifications /org/freedesktop/Notifications org.freedesktop.Notifications.SystemNoteInfoprint \"string:$*\""
}


dbus_method() {
    local dest=$1
    shift
    DBUS_REPLY=`dbus-send 2>&1 --system --type=method_call --print-reply --dest="$dest" $*`
}


dbus_result() {
    echo $DBUS_REPLY | cut -d ' ' -f 7 | tr -d \"
}


find_connection() {
    if dbus_method org.bluez /org/bluez org.bluez.Manager.ActivateService string:network; then
        NET_BUS=`dbus_result`

        if dbus_method "$NET_BUS" /org/bluez/network org.bluez.network.Manager.FindConnection string:"$BTADDR"; then
            # connection already exists
            CONN=`dbus_result`
        else
            # make new connection
            if dbus_method "$NET_BUS" /org/bluez/network org.bluez.network.Manager.CreateConnection string:"$BTADDR" string:"$PAN_ROLE"; then
                CONN=`dbus_result`
            fi
        fi
    fi
}


bnep_start() {
    if [ "x$CONN" != "x" ]; then
        infoprint "Connecting to $BTNAME ..."
        if dbus_method "$NET_BUS" $CONN org.bluez.network.Connection.Connect; then
            BNEPDEV=`dbus_result`

            ifconfig $BNEPDEV up
            RC=$?
            if [ $? != 0 ]; then
                infoprint "Connection failed"
            	exit 2
            fi

            killall udhcpc
            udhcpc -i $BNEPDEV
            infoprint "Connected to $BTNAME"
        else
            infoprint "Connection failed"
            exit 2
        fi
    fi
}


bnep_stop() {
    if [ "x$CONN" != "x" ]; then
        infoprint "Disconnecting ..."
        if dbus_method "$NET_BUS" $CONN org.bluez.network.Connection.Disconnect; then
            echo -n '' >/tmp/resolv.conf.lo
            infoprint "Disconnected from $BTNAME"
        else
            infoprint "Disconnecting failed"
        fi
    fi
}




infoprint "Searching for $BTNAME ..."
find_connection
if [ "x$CONN" = "x" ]; then
    infoprint "Could not find $BTNAME"
    exit 2
fi


case $COMMAND in
    connect)
        bnep_start
        ;;
    disconnect)
        bnep_stop
        ;;
esac

