#
#
#
import os
import re
import logging
from subprocess import Popen, PIPE, check_call

# logger = 
#
class AndroidAppPull:
  """
  Tools to discover and pull apps from Android device using adb
  """

  #
  def getAppsDir(self):
    dir_names = []
    stderr = ''
    # call adb shel command to parse the file system
    process = Popen(["adb", "shell", "ls", "-l", "/data/data"], stdout=PIPE, stderr=PIPE)
    stdout, stderr = process.communicate()

    if (0 < stdout.find('failed')):
      logging.error("Error executing adb shell")
      logging.info("Make sure adb is in root mode, 'adb root'")

    strings = stdout.split('\n')
    for sstr in strings:
      results = re.search(r'\s(\w+\.[\w|\.]+)', sstr)
      if results:
        dir_names.append(results.group(1))
    return dir_names

  # bdir:  base directory
  # fdir:  file directory
  def pullApp(self, bdir, fdir):
    logging.info("[{}]".format(fdir))
    cdir = bdir + os.path.sep + fdir
    try:
      check_call(["mkdir", cdir])
    except:
      logging.error("ERROR: problem creating directory {}".format(cdir))
      return 
    logging.info("Pulling data from directory {}".format("/data/data/"+cdir))
    process = Popen(["adb", "pull", "/data/data/"+fdir], stdout=PIPE, stderr=PIPE, cwd=cdir)
    stdout, stderr = process.communicate()
    return stdout, stderr


  def isADBRoot(self):
    retval = False
    process = Popen(["adb", "root"], stdout=PIPE, stderr=PIPE)
    stdout, stderr = process.communicate()
    # string "adbd is already running as root" will be returned
    if (0 < stdout.find('already running')):
      retval = True
    return retval

