#!/bin/sh

# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2013 Aleksander Morgado <aleksander@gnu.org>
#
# Based on libqmi's qmi-network script
#

print_usage ()
{
    echo "usage: $0 [DEVICE] [COMMAND]"
}

help ()
{
    echo "Usage: mbim-network [OPTIONS] [DEVICE] [COMMAND] - Simple network management of MBIM devices"
    echo
    echo "Commands:"
    echo "  start           Start network connection"
    echo "  stop            Stop network connection"
    echo "  status          Query network connection status"
    echo
    echo "Options:"
    echo "  --help          Show help options"
    echo "  --version       Show version"
    echo
}

version ()
{
    echo "mbim-network 1.12.4"
    echo "Copyright (2013) Aleksander Morgado"
    echo "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl-2.0.html>"
    echo "This is free software: you are free to change and redistribute it."
    echo "There is NO WARRANTY, to the extent permitted by law."
    echo
}

if [ $# -ne 2 ]; then
    if [ "$1" = "--help" ]; then
        help
        exit 0
    elif [ "$1" = "--version" ]; then
        version
        exit 0
    fi

    echo "error: missing arguments" 1>&2
    print_usage
    exit 255
fi

DEVICE=$1
COMMAND=$2
STATE_FILE=/tmp/mbim-network-state
PROFILE_FILE=/etc/mbim-network.conf

load_profile ()
{
    if [ -f $PROFILE_FILE ]; then
        echo "Loading profile..."
        . $PROFILE_FILE

        if [ "x$APN" != "x" ]; then
            echo "    APN: $APN"
        fi
    fi
}

save_state ()
{
    KEY=$1
    VAL=$2

    echo "Saving state... ($KEY: $VAL)"

    if [ -f $STATE_FILE ]; then
        PREVIOUS=`cat $STATE_FILE`
        PREVIOUS=`echo "$PREVIOUS" | grep -v $KEY`
        if [ "x$PREVIOUS" != "x" ]; then
            echo $PREVIOUS > $STATE_FILE
        else
            rm $STATE_FILE
        fi
    fi

    if [ "x$VAL" != "x" ]; then
        echo "$KEY=\"$VAL\"" >> $STATE_FILE
    fi
}

load_state ()
{
    if [ -f $STATE_FILE ]; then
        echo "Loading previous state..."
        . $STATE_FILE

        if [ "x$TRID" != "x" ]; then
            echo "    Previous Transaction ID: $TRID"
        fi
    fi
}

clear_state ()
{
    echo "Clearing state..."
    rm -f $STATE_FILE
}

#
# $ sudo mbimcli -d /dev/cdc-wdm0 --connect="Internet" --no-close
#   [/dev/cdc-wdm0] Successfully connected
#   [/dev/cdc-wdm0] Connection status:
#             Session ID: '0'
#       Activation state: 'activated'
#       Voice call state: 'none'
#                IP type: 'ipv4'
#           Context type: 'internet'
#          Network error: 'unknown'
#
connect ()
{
    # Always try to connect using a fresh session
    if [ "x$TRID" != "x" ]; then
        mbimcli -d $DEVICE --no-open=$TRID
        clear_state
    fi

    SUBSCRIBER_READY_CMD="mbimcli -d $DEVICE --query-subscriber-ready-status --no-close"
    echo "Querying subscriber ready status '$SUBSCRIBER_READY_CMD'..."

    SUBSCRIBER_READY_OUT=`$SUBSCRIBER_READY_CMD`
    echo $SUBSCRIBER_READY_OUT

    # Save the new TRID
    TRID=`echo "$SUBSCRIBER_READY_OUT" | sed -n "s/.*TRID.*'\(.*\)'.*/\1/p"`
    if [ "x$TRID" != "x" ]; then
        save_state "TRID" $TRID
    fi


    REGISTRATION_STATE_CMD="mbimcli -d $DEVICE --query-registration-state --no-open=$TRID --no-close"
    echo "Querying registration state '$REGISTRATION_STATE_CMD'..."

    REGISTRATION_STATE_OUT=`$REGISTRATION_STATE_CMD`
    echo $REGISTRATION_STATE_OUT

    # Save the new TRID
    TRID=`echo "$REGISTRATION_STATE_OUT" | sed -n "s/.*TRID.*'\(.*\)'.*/\1/p"`
    if [ "x$TRID" != "x" ]; then
        save_state "TRID" $TRID
    fi

    ATTACH_CMD="mbimcli -d $DEVICE --attach-packet-service --no-open=$TRID --no-close"
    echo "Attaching to packet service with '$ATTACH_CMD'..."

    ATTACH_OUT=`$ATTACH_CMD`

    # Save the new TRID
    TRID=`echo "$ATTACH_OUT" | sed -n "s/.*TRID.*'\(.*\)'.*/\1/p"`
    if [ "x$TRID" != "x" ]; then
        save_state "TRID" $TRID
    fi

    CONNECT_CMD="mbimcli -d $DEVICE --connect=$APN --no-open=$TRID --no-close"
    echo "Starting network with '$CONNECT_CMD'..."

    CONNECT_OUT=`$CONNECT_CMD`
    if [ $? -eq 0 ]; then
        echo "Network started successfully"
    else
        echo "Network start failed"
        echo $CONNECT_OUT
    fi

    # Save the new TRID
    TRID=`echo "$CONNECT_OUT" | sed -n "s/.*TRID.*'\(.*\)'.*/\1/p"`
    if [ "x$TRID" != "x" ]; then
        save_state "TRID" $TRID
    fi
}

#
# $ sudo mbimcli -d /dev/cdc-wdm0 --disconnect="0"
#   [/dev/cdc-wdm0] Successfully disconnected
#   [/dev/cdc-wdm0] Connection status:
#             Session ID: '0'
#       Activation state: 'deactivated'
#       Voice call state: 'none'
#                IP type: 'default'
#           Context type: 'internet'
#          Network error: 'unknown'
#
disconnect ()
{
    # Always close the session when disconnecting
    if [ "x$TRID" != "x" ]; then
        DISCONNECT_CMD="mbimcli -d $DEVICE --disconnect --no-open=$TRID"
    else
        DISCONNECT_CMD="mbimcli -d $DEVICE --disconnect"
    fi
    echo "Stopping network with '$DISCONNECT_CMD'..."

    DISCONNECT_OUT=`$DISCONNECT_CMD`
    if [ $? -eq 0 ]; then
        echo "Network stopped successfully"
    else
        echo "Network stop failed"
        echo $DISCONNECT_OUT
    fi

    clear_state
}

#
# $ sudo mbimcli -d /dev/cdc-wdm0 --query-connection-state  --no-close
# [/dev/cdc-wdm0] Connection status:
#         Session ID: '0'
#   Activation state: 'deactivated'
#   Voice call state: 'none'
#            IP type: 'default'
#       Context type: 'none'
#      Network error: 'unknown'
#
status ()
{
    if [ "x$TRID" != "x" ]; then
        STATUS_CMD="mbimcli -d $DEVICE --query-connection-state --no-close --no-open=$TRID"
    else
        STATUS_CMD="mbimcli -d $DEVICE --query-connection-state"
    fi
    echo "Getting status with '$STATUS_CMD'..."

    STATUS_OUT=`$STATUS_CMD`

    # Save the new TRID
    TRID=`echo "$STATUS_OUT" | sed -n "s/.*TRID.*'\(.*\)'.*/\1/p"`
    if [ "x$TRID" != "x" ]; then
        save_state "TRID" $TRID
    fi

    CONN=`echo "$STATUS_OUT" | sed -n "s/.*Activation state:.*'\(.*\)'.*/\1/p"`
    if [ "x$CONN" = "x" ]; then
        echo "error: couldn't get connection status" 1>&2
        exit 2
    else
        echo "Status: $CONN"
        if [ "x$CONN" != "xconnected" ]; then
            exit 64
        fi
    fi
}

# Main

# Load profile, if any
load_profile

# Load previous state, if any
load_state

# Process commands
case $COMMAND in
    "start")
        connect
        ;;
    "stop")
        disconnect
        ;;
    "status")
        status
        ;;
    *)
        echo "error: unexpected command '$COMMAND'" 1>&2
        print_usage
        exit 255
        ;;
esac

exit 0
