#!/system/bin/sh

# Replicant USB Networking
# ========================
#
# Copyright (C) 2011,2014 Paul Kocialkowski and Riku Saikkonen
# Copyright (C) 2017 Wolfgang Wiedmeyer <wolfgit@wiedmeyer.de>
#
# 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 3 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, see <http://www.gnu.org/licenses/>.

set -e

USB_IFACE="rndis0"

# OpenNIC DNS servers
DNS1="193.183.98.154"
DNS2="87.98.175.85"

start_rndis () {
    svc usb setFunction rndis
}

stop_rndis () {
    svc usb setFunction
}

if_up () {
    ifconfig $USB_IFACE up
}

if_down () {
    ifconfig $USB_IFACE down
}

clear_iface () {
    echo "Clearing network configuration"
    ndc network destroy 1
    ndc interface clearaddrs "$iface"
}

setup_iface () {
    gateway=$(ip route show 0.0.0.0/0 dev $USB_IFACE | cut -d\  -f3)

    if [ "$gateway" = "" ]; then
	echo "Error: no route available"
	echo "Make sure your PC is configured correctly for usb networking"
	exit 1
    fi

    echo "Your gateway is $gateway"
    ndc network create 1
    ndc network interface add 1 "$USB_IFACE"
    ndc network route add 1 "$USB_IFACE"  0.0.0.0/0 "$gateway"
    ndc resolver setnetdns 1 "" "$DNS1" "$DNS2"
    ndc network default set 1
}

configure () {
    clear_iface

    echo "Configuring DHCP, please wait"
    if_up

    if [ $(dhcpcd $USB_IFACE) ]; then
       echo "Error configuring DHCP"
    fi

    setup_iface

    echo "DHCP configured"
}

case "$1" in
    start1)
	echo "Starting Replicant USB networking, phase 1"
	start_rndis
	;;
    start2)
	echo "Starting Replicant USB networking, phase 2"
	configure
	;;
    stop)
	echo "Stopping Replicant USB networking"
	if_down
	stop_rndis
	;;
    *)
	echo "Usage: sh $0 {start1|start2|stop}"
	;;
esac

exit 0
