#!/bin/sh
# This program is free software: you can redistribute it and/or modify it
# under the terms of the the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the applicable version of 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, see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2012 Canonical, Ltd.

if [ -f "$(dirname $0)/shell-adb-common.sh" ]; then
    . "$(dirname $0)/shell-adb-common.sh"
else
    . "/usr/share/phabletutils/shell-adb-common.sh"
fi

export LC_ALL=C

usage() {
cat <<EOF
usage: $0 [OPTIONS]

Copies ACTIVE network manager connection into device

OPTIONS:
  -h	Show this message
  -s    Specify the serial of the device to install
  -n    Select network file
  -t    Timeout for waiting on network connection to become active.
        Default=$WAIT_TIMEOUT

  --skip-setup   Skip setting up a network-manager connection on the target.
  --skip-wait    Skip waiting for the network connection to become active.

EOF
}

OPTION_NETWORK_FILE=""
SKIP_SETUP=""
SKIP_WAIT=""
WAIT_TIMEOUT="80s"

ARGS=$(getopt -o n:s:t:h -l "help,skip-setup,skip-wait,timeout:" -n "$0" -- "$@")
if [ $? -ne 0 ] ; then
    exit 1
fi
eval set -- "$ARGS"

while true; do
    case "$1" in
        -h|--help)
            usage
            exit 0
            ;;
        -n)
            shift;
            OPTION_NETWORK_FILE=$1
            shift;
            ;;
        -s)
            shift;
            SERIAL="$1"
            shift;
            ;;
        -t|--timeout)
            shift;
            WAIT_TIMEOUT=$1
            shift;
            ;;
        --skip-wait)
            shift;
	        SKIP_WAIT=1
            ;;
	    --skip-setup)
            shift;
            SKIP_SETUP=1
            ;;
        --)
            shift;
            break;
            ;;
    esac
done


# exporting ANDROID_SERIAL to support multiple devices connected
# seamlessly
[ -z "$SERIAL" ] || export ANDROID_SERIAL="$SERIAL"

NETWORK_MANAGER=/etc/NetworkManager/system-connections

find_active_network() {
    nmcli_cmd="-t -f name,uuid,devices con status"
    if $(dpkg --compare-versions "$(nmcli --version|sed 's/^.* //')" gt 0.9.8.8); then 
        nmcli_cmd="-t -f name,uuid,device con show"
    fi
    wireless_adapter="$(nmcli -t -f device,type dev | egrep "wireless|wifi" | cut -d: -f1)"
    network_active_uuid="$(LC_ALL=C nmcli $nmcli_cmd | grep $wireless_adapter | cut -d: -f2)"
    if [ -z "$network_active_uuid" ]
    then
        echo "No active wifi network connection, exiting"
        exit 1
    fi
    network_file=$(sudo grep -H "$network_active_uuid" $NETWORK_MANAGER/* | grep uuid | cut -f1 -d:)

    echo "$network_file"
}

setup_connection() {
    if [ -z "$OPTION_NETWORK_FILE" ]; then
        network_file="$(find_active_network)"
    else
        network_file="$OPTION_NETWORK_FILE"
    fi

    if [ ! -f "$network_file" ]
    then
        echo "Network connection file \"$network_file\" cannot be read"
        exit 1
    fi

    echo Network file is $network_file

    if [ ! -r "$network_file" ]; then
        SUDO="sudo"
    fi
    SSID="$($SUDO grep ^ssid= "$network_file"|sed 's/^ssid=//')"
    KEY="$($SUDO grep ^psk= "$network_file"|sed 's/^psk=//')"

    # No PSK ? Let's check for WEP
    [ -z "$KEY" ] && KEY="$(sudo grep ^wep-key0= "$network_file"|sed 's/^wep-key0=//')"

    # Still no key ?
    if [ -z "$KEY" ]; then
        echo "Could neither find WEP nor WPA-PSK key !"
        exit 1
    fi

    echo Provisioning network on device
    adb shell "nmcli device wifi connect ${SSID} password '${KEY}' 2>/dev/null"

    echo
    echo Network setup complete
}

wait_for_network() {
    timeout $WAIT_TIMEOUT sh <<EOF
        while true ; do
	    # adb shell doesn't return errors from the command
	    # also, ping can be blocked like it is in the QA lab. however,
	    # the logic below will ensure that DNS resolution part of the
	    # ping worked, which should be enough to prove to us that the
	    # network stack is ready
            if adb shell ping -c1 launchpad.net | grep PING ; then
                exit 0
            fi
            done
EOF
    if [ $? -ne 0 ] ; then
        echo "Network connection failed to become active."
	exit 1
    fi
}

check_devices

[ -n "$SKIP_SETUP" ] || setup_connection
[ -n "$SKIP_WAIT" ] || wait_for_network
