#!/usr/bin/env python3
# Copyright (c) 2015 Quanta Research Cambridge, Inc.

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy,
# modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from __future__ import print_function

import os, sys, time
from adb import adb_commands
from adb import common

timebound = 5
#scriptdir=os.path.dirname(sys.argv[0])
#sys.path.append(scriptdir)
command_list = ['shell', 'push', 'pull', 'root', 'reboot']

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('cadb <ipaddr> <command> <args>')
        sys.exit(-1)
    ipaddr = ''
    args = sys.argv[1:]
    if args[0] not in command_list:
        ipaddr = args[0]
        args = args[1:]
    if 'RUNPARAM' in os.environ:
        ipaddr=os.environ['RUNPARAM']
    if ipaddr == '':
         print('cadb: missing address')
         sys.exit(-1)
    print('connecting to %s' % ipaddr)
    starttime = time.clock()
    count = 0
    while True:
        try:
            connection = adb_commands.AdbCommands.ConnectDevice(serial=ipaddr)
            print('connect ok', count, time.clock() - starttime)
            break
        except:
            pass
        if time.clock() - starttime > timebound:
            print('cadb: connection attempt timed out')
            sys.exit(-1)
        count += 1
    try:
        if args[0] == 'shell':
            for line in connection.StreamingShell(' '.join(args[1:])):
                sys.stdout.write(line)
        elif args[0] == 'push':
            for filename in args[1:-1]:
                connection.Push(filename, args[-1])
        elif args[0] == 'pull':
            connection.Pull(args[1], args[2])
        elif args[0] == 'root':
            try:
                connection.Root()
            except:
                pass    # connection always fails as adbd reboots...
        elif args[0] == 'reboot':
            connection.Reboot()
        connection.Close()
    except:
        print('cadb: operation failed', args[0])
        sys.exit(-1)
    sys.exit(0)
