#! /bin/sh
 
#    Feb 06/09 - F.Majaess
 
#id  arlibdel- Script to delete object file(s) from archive library.
 
#    AUTHOR  - F.Majaess
 
#hd  PURPOSE - "arlibdel" script is used to handle the deletion of 
#hd            object file(s) from one or more archive libraries. 
#hd            Note: The script must be invoked from within the
#hd                  subdirectory where the archive libraries reside.
#hd                        
#pr  PARAMETERS:
#pr
#pr    POSITIONAL
#pr
#pr       arclist = list of local archive libraries to process.
#pr                 (each having ".a" suffix)
#pr       objlist = list of object filenames to delete from "arclist".
#pr                 (each having ".o" suffix and it can be in upper 
#pr                  or lower case) 
#pr
 
#ex  EXAMPLE:
#ex
#ex    arlibdel libLOSUB_comm_*.a alatlon.o angles.o 
#ex
#ex  The above will result in deleting 'alatlon.o angles.o" from 
#ex  archive libraries list based on "libLOSUB_comm_*.a" expansion.
#ex  
#ex    arlibdel libLOSUB_model_gcm15x_openmp.a abcvdh6.o
#ex
#ex  The above will handle the deletion of 'abcvdh6.o" from 
#ex  "libLOSUB_model_gcm15x_openmp.a" archive library.
#ex  

ArcList=''
ObjList=''
Abort='no'
for arg in $@
do
  case $arg in
        -x) set $arg                   ;;
       *=*) eval $arg                  ;;
       *.a) ArcList="$ArcList $arg"    ;;
       *.o) ObjList="$ObjList $arg"    ;;
         *) echo "Arlibdel: Invalid argument --> $arg <--"
            Abort='yes'                ;;
  esac
done

#  Abort if any invalid argument was detected

if [ "$Abort" = 'yes' ] ; then
  echo ""; echo "Arlibdel: Please correct ..."
  exit 1
fi

if [ -n "$ArcList" -a -n "$ObjList" ] ; then
 # For valid list of archive libraries and object files 
 
 # Prepare "string" based on "ObjList" to be used by "egrep" 

 AwkObjList=''
 for Obj in $ObjList
  do
   if [ -z "$AwkObjList" ] ; then
    AwkObjList='^'"$Obj"
   else
    AwkObjList="$AwkObjList"'|^'"$Obj"
   fi
  done
 
 # Loop over the archive libraries.

 for Arc in $ArcList
  do
   if [ -s "./$Arc" ] ; then


    if [ "$OS" = 'AIX' ] ; then

     # Adjust for 32/64 object libraries under AIX.

    #float1_lib=`echo $Arc | sed -e 's/^.*_float1.a *$/Yes/'`
     float1_lib=`echo $Arc | sed -e 's/^.*_float1.a *$/Yes/' -e 's/^.*_float1_xlf[0-9]*.a *$/Yes/' `
     if [ "$float1_lib" = 'Yes' ] ; then
       Optns='-X32'
     else
       Optns='-X64'
     fi
    else
     Optns=''
    fi
    
    # Obtain list of matching object files found in the archive library

    ObjListx=`ar $Optns -t ./$Arc | egrep -i "$AwkObjList" | tr '\012' '\040'`
    if [ -n "$ObjListx" ] ; then

     # Delete matching object files 

       ar $Optns -d ./$Arc $ObjListx &&
       echo "ar $Optns -d ./$Arc $ObjListx" || echo "Problem processing: ar $Optns -d ./$Arc $ObjListx !"
    else
      echo "Arlibdel: Skipped $Arc ; no matching object files"
    fi
   else
    echo "Arlibdel: Skipped Invalid archive library $Arc !"
   fi
  done

fi
