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


def androidPullData():
  dir_names = []
  # 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()  
  strings = stdout.split('\n')
  for sstr in strings:
    results = re.search(r'\s(\w+\.[\w|\.]+)', sstr)
    if results:
      dir_names.append(results.group(1))

  for fdir in dir_names:
    print "[{}]".format(fdir)
    ret = check_call(["mkdir", fdir])
    if (ret > 0):
      print "ERROR: problem creating directory {}".format(ret)
    else:
      print "Pulling data from directory {}".format("/data/data/"+fdir)
      process = Popen(["adb", "pull", "/data/data/"+fdir], stdout=PIPE, stderr=PIPE, cwd=fdir)
      stdout, stderr = process.communicate()

    # if stderr:
    #   print "ERROR: {}".format(stderr)
    # else:
    #   print "[COMPLETE]"
  # print "COMPLETED!!!"
  # print "STDERR ==\n {}".format(stderr)
  # print "STDOUT == n {}".format(stdout)


def adbCheck():
  # check that adb is executable
  # check that adb is in root mode
  return True


def main():
  if adbCheck():
    androidPullData()
  return


if __name__ == "__main__":
  main()
