#!/usr/bin/env python

#============================================================================
#
# @file LibSizeCheck.py
#
# GENERAL DESCRIPTION
#   Unified script for checking each lib size with each lib size maximum limit
#
# Copyright 2019 by Qualcomm Technologies, Inc.
#                 All Rights Reserved.
#               QUALCOMM Proprietary/GTDR
#
#----------------------------------------------------------------------------
#
#                          EDIT HISTORY FOR MODULE
#
# This section contains comments describing changes made to the module.
# Notice that changes are listed in reverse chronological order.
#
# when       who     what, where, why
# --------   ---     -----------------------------------------------------------
# 04/29/19   yps     Initial release
from optparse import OptionParser
import os
import sys
import re
import json
 
sys.path.append(os.path.join(os.path.dirname(sys.argv[0]),'..'))
from delcomments import *

def main():
  str=[]
  parser = OptionParser()

  parser.add_option('-m', '--mapitoutputfile', default="",
                    help="Per lib/driver size break-up file generated by mapit.py" + \
                         "Example: \n" + "  -m XBLLoader_mapit_bootimem_ocimem.txt", )
                         
  parser.add_option('-c', '--config', default="",
                    help="Input json file with maximum allowed size for each lib/driver " + \
                         "Example: \n  -c libssizecfg.json ")
                          

  (options, args) = parser.parse_args()
  if options.config:
    if not os.path.exists(options.config):
      return 0
    else:
      libconfg=remove_json_comments(options.config,None)
      libconfigdirt = json.loads(libconfg)
  else:
    print >>sys.stderr,"Please input config file"
    return 0

    
  try:
    f = open(options.mapitoutputfile,"r")
  except IOError:
    print options.maptxt + "does not exist!"
    sys.exit(2)
  for line in f.readlines():       
      str = line.split()
      if (str[0] == "CODE"):
        continue;
      if (str[7] == "Overall"):
        break;
      if(long(str[5]) > long(libconfigdirt['loaderlibs'][str[7].split(".")[0]]['maximum size'])):
        print >>sys.stderr, "ERROR: ",str[7]," size (",str[5],") exceeds the maximum limit(",libconfigdirt['loaderlibs'][str[7].split(".")[0]]['maximum size'], ")!!!"
        print >>sys.stderr, "Please optimize the lib size!!!"
        sys.exit(1)
  return 0
  
if __name__ == "__main__":
  main()  
