#!/usr/bin/python3

"""
@file
@ingroup ngcdcsExpDrvList
@copyright
  SPDX-FileCopyrightText: 2026 European Southern Observatory (ESO)
  SPDX-License-Identifier: LGPL-3.0-only

"""

import os
import sys
import glob
import subprocess

##
# Exposure driver module loader
#
def ExpDrvModFind(fullPath=False):

    modList = []

    #
    # Get shared objects search path
    #
    p = os.getenv('LD_LIBRARY_PATH', "").split(":")
    #p = []
    if len(p) == 0:
        e = os.getenv('VLTROOT', "")
        if e != "":
            p.append(e+"/lib")
        e = os.getenv('INTROOT', "")
        if e != "":
            p.append(e+"/lib")

    #
    # Search shared objects with qualified signature 
    #
    for ele in p:
        if ele != "":
            for lib in glob.glob(ele+"/*.so"):
                mod = os.path.splitext(os.path.basename(lib))[0]
                if mod[0:3] == "lib":
                    mod = mod[3:]
                signature = "_ngcdcs_expdrv_"+mod

                #
                # Call 'nm' and grep for signature
                #
                nm = subprocess.Popen(['nm', lib], stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
                grep = subprocess.Popen(['grep', '-w', signature],
                                        stdin=nm.stdout,
                                        stdout=subprocess.PIPE)
                (output, err) = grep.communicate()
                stat = grep.returncode
                
                if (stat == 0):
                    #
                    # Append to available modules list
                    #
                    if fullPath:
                        modList.append([mod, lib])
                    else:
                        modList.append([mod])

    return modList

#
# Find modules
#
flag = False
if len(sys.argv) > 1:
    if sys.argv[1] == "-p":
        flag = True
modList = ExpDrvModFind(flag)
for mod in modList:
    print('%s' % ' '.join(mod))

#___oOo___

