#
#
#
import os
import argparse
import time
import logging
from libs import fingerprint
from libs import toolbox
from libs import android
from subprocess import Popen, PIPE, check_call

BASE_DIR    = "data"
FP_BASE_DIR = "fingerprints"


def main():
  # logging.basicConfig(filename='dbfp.log', level=logging.DEBUG)
  logging.basicConfig(level=logging.DEBUG)
  parseArgs()

#
def compareFingerprintDir(filein, filejson, fpdir):
  db = fingerprint.DBSchema()

#
def compareFingerprint(filein, filejson):
  db = fingerprint.DBSchema()
  db.scanDBFile(filein)
  db.compareDB(filejson)

#
def createFingerprint(filein, fileout, verbose, app_name, app_ver, notes):
  db = fingerprint.DBSchema()
  retVal = db.scanDBFile(filein)
  if (retVal > 0):
    fh = open(fileout, "w")
    if verbose:
      db.debugFingerprint()
    if app_name:
      db.setAppName(app_name)
    if app_ver:
      db.setAppVer(app_ver)
    if notes:
      db.setNotes(notes)
    db.writeFingerprint(fh)
    fh.close()
  else:
    print db.getErrorString(retVal)

#
def fingerprintDir():
  ap = android.AndroidAppPull()
  isRoot = ap.isADBRoot();
  if (not isRoot):
    print "ERROR: adb is not running as root, exec 'adb root'"
    return

  if (not mkdir(BASE_DIR)):
    return
  if (not mkdir(FP_BASE_DIR)):
    return

  dir_names = ap.getAppsDir()
  for dir_name in dir_names:
    ap.pullApp(BASE_DIR, dir_name)
    __createFingerprint(dir_name)

#
def __createFingerprint(dir_name):
  try:
    cdir = BASE_DIR + os.path.sep + dir_name + os.path.sep + "databases"
    logging.info("cdir=={}".format(cdir))
    files = os.listdir(cdir)
  except:
    # not finding a databases folder is normal, not all apps use sqlite
    return
  db = fingerprint.DBSchema()
  fdir = FP_BASE_DIR + os.path.sep + dir_name
  if (not mkdir(fdir)):
    logging.error('Error creating directory "{}"'.format(fdir))
    return
  for filein in files:
    ddir = cdir + os.path.sep + filein
    logging.info('Parsing file "{}"'.format(ddir))
    retVal = db.scanDBFile(ddir)
    if (retVal > 0):
      fname = dir_name + "__" + filein + "__dbfp" + ".json"
      fdir_name = fdir + os.path.sep + fname
      fh = open(fdir_name, "w")
      db.setAppName(dir_name)
      db.writeFingerprint(fh)
      fh.close()

#
def mkdir(fdir):
  retval = False
  try:
    check_call(["mkdir", fdir])
    retval = True
  except:
    logging.error('ERROR: problem creating directory "{}"'.format(fdir))
  return retval

#
def parseArgs():
  print '***** ***** ***** *****'
  print '   DB Fingerprint'
  print '***** ***** ***** *****\n'
  fileout = ''
  timestr = time.strftime('%Y-%m-%d_%H%M%S', time.localtime(time.time()))
  parser = argparse.ArgumentParser(description='Fingerprint a sqlite database based on its schema')
  parser.add_argument('-f', '--file', required=False)
  parser.add_argument('-fd', '--fpdir', required=False, help="path to dirctory of fingerprint files")
  parser.add_argument('-fp', '--fp', required=False, help="fingerprint file to use in comparison")
  parser.add_argument('-an', '--app_name', required=False)
  parser.add_argument('-av', '--app_version', required=False)
  parser.add_argument('-n', '--notes', required=False)
  parser.add_argument('-pull', '--pull', required=False, action='store_true')
  parser.add_argument('-v', '--verbose', action='store_true')
  # parser.add_argument('-t', '--title', required=False)
  args = parser.parse_args()

  if (args.file):
    filename = toolbox.ToolBox.parseFilename(args.file)
    fileout = filename + "_" + timestr + '.json'
    createFingerprint(args.file, fileout, args.verbose, args.app_name, args.app_version, args.notes)
  elif (args.fp and args.fpdir):
    compareFingerprintDir(args.file, args.fp, args.fpdir)
  elif (args.fp):
    compareFingerprint(args.file, args.fp)      
  elif (args.pull):
    fingerprintDir()    
  else:
    parser.print_help()

  return


  if (args.pull):
    fingerprintDir()    
    return

  if (args.file is None) or (args.fp is None) or (args.pull is None):
    parser.print_help()
    return

  # compare a sqlite database file to all fingerprints
  if (args.fp and args.fpdir):
    compareFingerprintDir(args.file, args.fp, args.fpdir)
    return

  # compare a sqlite database file to a fingerprint
  if (args.fp):
    compareFingerprint(args.file, args.fp)
    return

  # create a fingerprint from the sqlite file
  filename = toolbox.ToolBox.parseFilename(args.file)
  fileout = filename + "_" + timestr + '.json'
  createFingerprint(args.file, fileout, args.verbose, args.app_name, args.app_version, args.notes)


if __name__ == "__main__":
  main()
