#
#
#
import argparse
import time
from libs import fingerprint
from libs import toolbox


def main():
  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 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('-v', '--verbose', action='store_true')
  # parser.add_argument('-t', '--title', required=False)
  args = parser.parse_args()

  if (args.file is None) and (args.fp is None):
    parser.print_help()
    exit()


  # compare a sqlite database file to all fingerprints
  if (args.fp and args.fpdir):
    compareFingerprints(args.file, args.fp, args.fpdir)
  # compare a sqlite database file to a fingerprint
  if (args.fp):
    compareFingerprint(args.file, args.fp)
  # 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()
