#!/usr/local/lcls/package/python/current/bin/python

import os
import sys
import re
import getopt
# Do not have two imports in one line. Makes it unreadable.

# Author: N. Balakrishnan
# Created: 09/12/2017
# Modified:
#           10/06/2017 N.Balakrishnan (namrata)
#           Update to use default option as pv name
#
# Usage: python findlink.py [OPTION] [STRING]
# Description: Searches IOC.dbDumpRecord files for PVs containing a specific string as a link
filename = None
path = None
pv_name = None
only_bad = False
def usage(prog_name):
    print("\n%s: Find all the PV`s the given PV is linked to" % prog_name)
    print("Usage:")
    print("   %s -h  Shows this usage message" % prog_name)
    print("   %s -b  Search only for bad ca links" % prog_name)
    print("   %s -d  Lists the directory to search in" % prog_name)
    print("   %s -p  The PV to find links to" % prog_name)
    print("   %s default  The PV to find links to" % prog_name)

try:
   opts, args = getopt.getopt(sys.argv[1:],'hbd:p:', ['help','bad','dir=','pv='])
except getopt.GetoptError, err:
   print str(err)
   usage(sys.argv[0])
   sys.exit(2)
for opt,arg in opts:
   if opt in ('-h','--help'):
      usage(sys.argv[0])
      sys.exit()
   elif opt in ('-b', '--bad'):
      only_bad = True
   elif opt in ('-d', '--dir'):
      path = arg
   elif opt in ('-p', '--pv'):
      pv_name = arg
   else:
      print('arg given is' + arg )
      pv_name = arg
      usage(sys.argv[0])
      sys.exit(1)

# Include pv to be default
# When pv name is entered as an argument
arglen = len(sys.argv)
if pv_name is None:
   pv_name = sys.argv[-1]

if path is None:
   print("\nNo path specified. $IOC_DATA will be searched")
   # In dev- test
   #path ="/u/cd/namrata/pythonLearnBed/testIocData"
   # In dev
   #path = "/nfs/slac/g/lcls/epics/ioc/data"
   # In prod
   path = "/u1/lcls/epics/ioc/data"
   if only_bad:
      filename = "iocInfo/IOC.dbcar"
   else:
      filename = "iocInfo/IOC.dbDumpRecord"

if pv_name is None:
   print("\nNo pv name specified")
   usage(sys.argv[0])
   sys.exit()

#python2.7 update this to print(msgn,end"") once python3
print"\nPath to be searched:",
print(path)
#print "Links to PV:",
print"Links to PV:",
print(pv_name)

# Put the ioc directory names in the iocData directory in a list
dir_list = os.listdir(path)

found = 0
record_name = ''

# Function to find the record name which has the PV
def display_man(line, record):
   if line == record:
      # This prints the record name
      # Remove everything before the name
      pv = re.sub(r'.*,"','',record)
      # Remove everything after the name
      msgn = pv.split('"')[0]
      print(msgn)
   else :
      # This prints the link to the record where you find the pv
      # Remove everything before the record name
      pv = re.sub(r'.*,"','',record)
      # Remove everything after the record name
      msgn = pv.split('"')[0]
      # Get the record name out
      msg = line
      # Remove everything before the name
      pv = re.sub(r'.*field','',msg)
      # replace ," with =
      pv1 = re.sub(r',"','=',pv)
      # remove everything after the record name
      pv2 = pv1.split('"')[0]
      #Print the record and link dont print the first character.
      print(msgn+'.'+pv2[1:])

# This will go through all the files in the directory by looping through
for dir_name in dir_list:
   if filename == None:
      fileNpath = os.path.join(path,dir_name)
   else :
      fileNpath = os.path.join(path,dir_name,filename)
   try :
      with open(fileNpath) as f:
         contents = f.read()
         # Split builds list of words from a string
         if only_bad:
            words_list = contents.split('\n')
         else:
            words_list = contents.split()
         # Count the approximate number of words in the file.
         #counts= contents.count(pv_name)
         counts= len(re.findall(pv_name, contents))
         #Don't count the record itself, that's not a link
         counts = counts - len(re.findall(r"record.*" + pv_name, contents))
         if counts >= 1:
            found = found + 1
            msg = "\nOccurence in " + dir_name + " = " + str(counts)
            #python 2.7 update with print()
            # Underline the msg and then change back to default
            print '\033[4m' + msg+ '\033[0m'
            for i, line in enumerate(words_list):
               if only_bad:
                  # Search for links TO the PV, exclude FROM
                  if re.search(r'-->.*',line):
                    if re.search(pv_name, re.search('-->.*',line).group()):
                     print line
               else:
                  # store record line so if pvlink found record is known.
                  if line.startswith('record'):
                     record_name = line
                  else:
                     # if pv is found in the line find record and link
                     #if pv_name in line:
                     if re.search(pv_name, line):
                        display_man(line,record_name)
   except IOError:
      pass
if found == 0:
   print("\nNo link found for "+ pv_name)
