#!/bin/ash

#
# App : AutoDisconnect
# Url : https://garage.maemo.org/projects/autodisconnect/
# Version: 0.4
# Author: Aymeric Brisse <aymeric.brisse@gmail.com>
# License: GNU General Public License
#

# ---------------------------------------------------------------------------
# FUNCTIONS
# ---------------------------------------------------------------------------

GC_ROOT="/apps/autodisconnect"

# ---------------------------------------------------------------------------
getvalue()
# ---------------------------------------------------------------------------
# Get Conf value
#
{
    echo "`gconftool-2 -g $GC_ROOT/param_$1`"
}

# ---------------------------------------------------------------------------
readparameters()
# ---------------------------------------------------------------------------
{
    # How often to test for inactivity (min)
    g_samplerate=`getvalue "bluetooth_interval"`

    # Enable logging
    g_logging=true

    # Notifications
    g_notifications=`getvalue "notifications"`

    # Where to store the logfile. This is cleared when it goes over 50k.
    logfile=/var/log/autodisconnect.log

    # Convert min interval to sec interval
    g_samplerate=$((g_samplerate*60))
}

# ---------------------------------------------------------------------------
killsiblings()
# ---------------------------------------------------------------------------
# Kill other instances of the process
#
{
    TmpFile=/tmp/$(basename $0).tmp

    `ps | egrep 'S[ ]*/bin/ash[ ]*/opt/autodisconnect/autodisconnect-bluetooth' | sed 's/^[ ]*\([0-9]*\) .*$/\1/g' > $TmpFile`

    while read Pid
    do
        [[ -n "$Pid" -a "$Pid" -ne "$$" ]] && {
            logentry "<Kill $Pid>"
            kill -KILL $Pid 2>/dev/null
        }
    done < $TmpFile
}

# ---------------------------------------------------------------------------
init()
# ---------------------------------------------------------------------------
# Init
#
{
    # Log
    logentry "<@Start>"

    # Allow dbus to work
    [[ -e /tmp/dbus-info ]] && eval `cat /tmp/dbus-info`

    export DBUS_SESSION_BUS_ADDRESS \
           DBUS_SESSION_BUS_PID \
           DBUS_SESSION_BUS_WINDOWID

    # Don't let log file get too big
    if [[ -w "$logfile" ]]; then
        size=`stat $logfile | grep Size | awk '{ print $2; }'`
        [[ "$size" -gt 50000 ]] && :>$logfile
    fi
}

# ---------------------------------------------------------------------------
logentry()
# ---------------------------------------------------------------------------
# Send a string to this function to append it to the log file
#
# Arg 1 - The text to log
{
    [[ "$g_logging" = true ]] && {
        echo -e "[`date +%T`][$$][Bluetooth] $1" >> $logfile
    }
}

# ---------------------------------------------------------------------------
osnotify()
# ---------------------------------------------------------------------------
# Send a string to this function to generate a system popup
#
# Arg 1 - The text to display
{
    [[ "$g_notifications" = true ]] && {
        /usr/bin/dbus-send --type=method_call \
        --dest=org.freedesktop.Notifications \
        /org/freedesktop/Notifications \
        org.freedesktop.Notifications.SystemNoteInfoprint \
        string:"$1"
    }
}

# ---------------------------------------------------------------------------
disconnect()
# ---------------------------------------------------------------------------
# Disconnect current connection
#
# No args
{
    dbus-send --system --type=method_call \
        --dest=org.bluez $(dbus-send --system --print-reply \
        --dest=org.bluez / org.bluez.Manager.ListAdapters | \
        awk -F'"' '/at/ {print $2}') org.bluez.Adapter.SetProperty \
        string:Powered variant:boolean:false
}

# ---------------------------------------------------------------------------
isrunning()
# ---------------------------------------------------------------------------
# Check if a process is running
#
# Arg 1 - the service
{
	test -n "`ps | grep "$1" | grep -v grep`"
}

# ---------------------------------------------------------------------------
readbluetooth()
# ---------------------------------------------------------------------------
# Check Bluetooth Status
#
# No args
{
    bluetooth_status_old=$bluetooth_status
    bluetooth_connected_old=$bluetooth_connected
    
    if [[ -n "`/usr/sbin/hciconfig | grep RUNNING`" ]]; then
        bluetooth_status=true
        if [[ "`/usr/bin/hcitool con | wc -l`" -gt 1 ]]; then
            bluetooth_connected=true
        else
            bluetooth_connected=false
        fi
    else
        bluetooth_status=false
        bluetooth_connected=false
    fi    
}


# ---------------------------------------------------------------------------
main()
# ---------------------------------------------------------------------------
# Main entry point
#
{
    # Read parameters
    readparameters

    # Init -> dbus & log
    init   
 
    readbluetooth    
    
    # MONITORING LOOP
    while true
    do
        sleep $g_samplerate

        readbluetooth

        # Check the bluetooth status
        if [[ "$bluetooth_status" = true -a "$bluetooth_status_old" = true -a "$bluetooth_connected" = false -a "$bluetooth_connected_old" = false  ]]; then

            exception_apply=false

            # Check if the FM Radio Application is not running
            if `isrunning "/usr/bin/FMRadio"`; then
                exception_apply=true
                logentry "bluetooth checked (fm_radio)"
            fi

            # ... block for other exceptions
            
            if [[ $exception_apply = false ]]; then
                bluetooth_status=false
                bluetooth_connected=false
                disconnect
                osnotify "AutoDisconnected has disabled the inactive Bluetooth"
                logentry "bluetooth closed (inactive)"
            fi

        else            
            logentry "bluetooth checked"
        fi

    done
    
}

# ---------------------------------------------------------------------------
# RUNTIME
# ---------------------------------------------------------------------------

# Kill every instances already running
killsiblings

g_check_bluetooth=`getvalue "bluetooth_enable"`
if [[ "$g_check_bluetooth" = true ]]; then
    main
    logentry "<Stop>"
fi

exit 0

