#!/usr/bin/env python
#  encoding=utf-8

import os, os.path
import argparse
import sys

from cmd import call
from cmd import getAdb
import adbdevice

# BASE_DIR="F:/release"
BASE_DIR=""

def getApks(path, filters):
    apks = os.listdir(path)
    apks = filter(lambda filename: filename.endswith('.apk'), apks)
    if filters is not None:
        def myfilterfun(filename):
            for f in filters:
                if f not in filename:
                    return False
            return True
        apks = filter(myfilterfun, apks)
    apks = map(lambda filename: os.path.join(path, filename), apks)
    return apks


def getNewst(apks):
    if len(apks) == 0:
        return None
    apks = sorted(apks, cmp=lambda fa, fb: int(os.path.getmtime(fb) - os.path.getmtime(fa)))
    return apks[0]


def filterApks(fileorpath, filters):
    apk = fileorpath
    if os.path.isdir(fileorpath):
        apks = getApks(fileorpath, filters)
        if len(apks) == 0:
            print('can not found apk file in %s ' % fileorpath)
            exit(1)
        apk = getNewst(apks)
    return apk


def install(apks, serials):
    adb = getAdb()
    for apk in apks:
        for serial in serials:
            cmd = '%s -s %s install -r "%s"' % (adb, serial, apk)
            call(cmd, True)


# -------------- main ----------------
if __name__ == '__main__':
    parser = argparse.ArgumentParser(usage='%(prog)s [options] [path]',
        description='install apk file.')
    parser.add_argument('-f', '--filter', nargs='*',
        help='filtered by file name')
    parser.add_argument('path', nargs='?')
    adbdevice.addArgumentParser(parser)

    args = parser.parse_args()

    isOk, serials = adbdevice.doArgumentParser(args)
    if isOk:
        exit(0)

    path = args.path if args.path is not None else '.'
    path = os.path.abspath(os.path.join(BASE_DIR, path))

    apks = filterApks(path, args.filter)

    if serials is not None and apks is not None:
        install([apks], serials)

@@ -125,16 +125,31 @@
  getAdb%0A
+import apkinfo%0A
 import a
@@ -1129,16 +1129,21 @@
  serials
+, run
 ):%0A    a
@@ -1164,24 +1164,118 @@
     
-for apk in apks:
+last = len(apks) - 1%0A    for i in range(0, len(apks)):%0A        apk = apks%5Bi%5D%0A        isrun = run and last == i
 %0A   
@@ -1379,16 +1379,26 @@
         
+ _, isOk =
  call(cm
@@ -1406,16 +1406,222 @@
 , True)%0A
+            print(isOk)%0A            if isOk and isrun:%0A                activity = apkinfo.parse(apk)%0A                cmd = '%25s -s %25s shell am start %22%25s%22' %25 (adb, serial, activity)%0A                call(cmd)%0A
 %0A%0A# ----
@@ -1884,16 +1884,114 @@
  name')%0A
+    parser.add_argument('-r', '--run', action=%22store_true%22,%0A        help='run app after install')%0A
     pars
@@ -2416,10 +2416,20 @@
  serials
+, args.run
 )%0A

support start app aflter install it