#!/usr/bin/env python

import os
import re
import sys
import time
import nmap
import netifaces
from netaddr import IPNetwork

PORT = 5555


def connectToDevice(ip):
    # Connect to an android device
    result = os.popen("adb connect " + ip + ":" + str(PORT)).read()
    if result.find("connected") != -1:
        return True
    else:
        return False


def getDecidesIDs(adbDevices):
    # Get all device IDs connected in an USB port
    return re.findall('(.*?)\tdevice', adbDevices)


def getIPfromDeviceID(deviceID):
    # Find ip from the device connect in USB port
    return os.popen("adb -s " + deviceID + " shell ip route | grep wlan0 | awk {\'if( NF >=9){print $9;}\'}").read().rstrip()


def verifyIfNotConnected(adbDevices, ip):
    # Verify if the device is already connected (wifi)
    return adbDevices.find(ip) == -1


def getConnectedNetworks():
    networks = []
    cards = netifaces.interfaces()
    for card in cards:
        iface_details = netifaces.ifaddresses(card)
        if netifaces.AF_INET in iface_details:
            ip = iface_details[netifaces.AF_INET][0]['addr']
            mask = iface_details[netifaces.AF_INET][0]['netmask']
            cidr = str(IPNetwork('%s/%s' % (ip, mask)).cidr)
            if(not cidr.startswith("127.0.0")):
                networks.append(cidr)
    return networks


def getNetworkDevices():
    devices = []

    for network in getConnectedNetworks():
        hosts = nm.scan(
            hosts=network,
            ports=str(PORT),
            arguments=""
        )

        devices.extend([host for host in hosts['scan'] if hosts['scan']
                        [host]["tcp"][PORT]["state"] == "open"])
    return devices


nm = nmap.PortScanner()

while True:

    devices = getNetworkDevices()

    adbDevices = os.popen("adb devices").read()

    for deviceID in getDecidesIDs(adbDevices):
        ip = getIPfromDeviceID(deviceID)
        if(ip != "" and ip not in devices and verifyIfNotConnected(adbDevices, ip)):
            os.popen("adb -s " + deviceID + " tcpip " + str(PORT))
            print("PORT 5555 open for " + ip)

    devicesToConnect = [ip for ip in devices if ip not in adbDevices]

    for ip in devicesToConnect:
        print("Detected new device to connect: " + ip)
        if (connectToDevice(ip)):
            print("Connected to " + ip)
        else:
            print("Failed to connected to " + ip)
