#!/bin/sh

BASEDIR=$(dirname $0)
cd $BASEDIR

extractOdbcFromBinary()
{
   # ldd is going to print something like:
   #     linux-vdso.so.1 =>  (0x00007ffc93adf000)
   #     libodbc.so.2 => /usr/lib64/libodbc.so.2 (0x0000003009000000)
   #     libdl.so.2 => /lib64/libdl.so.2 (0x00000033cba00000)
   # so we:
   # - grab the line with `grep`
   # - extract the path with `sed` using:
   #   - `^.*\s*`  (ignore everything until the `>` plus the whitespace)
   #   - `\(\S*\)` (capture until the first whitespace)
   #   - `.*$`     (ignore everything until the end of the string)
   #   - `\1`      (substitute the string with the captured string)
   #   - `p`       (print the substituted line)
   ldd "$1" | grep libodbc.so.2 | sed -n 's|^.*>\s*\(\S*\).*$|\1|p'
}

ODBCLIB=libodbc.so.2
DB2INSTANCE=<DB2INSTANCE>
export DB2INSTANCE
BESServerConfigPath="/var/opt/BESServer/besserver.config"
export BESServerConfigPath
BES_LIBPATH=.
export BES_LIBPATH
AIRGAPDIR="airgap"

$BES_LIBPATH/Airgap $*
RET=$?

if [ $# -eq 2 -a "-remotedir" = "$1" -a -d "$2/$AIRGAPDIR" ]; then
   if [ $RET -eq 0 ]; then
      cp "$(extractOdbcFromBinary $BES_LIBPATH/Airgap)" "$2/$AIRGAPDIR"
      tar -C "$2" -cf "$2/$AIRGAPDIR.tar" $AIRGAPDIR
   fi
   rm -rf "$2/$AIRGAPDIR"
elif [ $# -eq 1 -a "-run" = "$1" -a -d "./$AIRGAPDIR" ]; then
   if [ $RET -eq 0 ]; then
      cp "$(extractOdbcFromBinary $BES_LIBPATH/Airgap)" "$2/$AIRGAPDIR"
      tar -cf $AIRGAPDIR.tar $AIRGAPDIR
   fi
   rm -rf $AIRGAPDIR
fi

#.. end of file

