#!/bin/sh
#
# Script to make a static version of the Bacula
#  File daemon and to copy it to the current
#  directory.
#
export LANG=C
srcdir=$1

function find_config {
  CONFPATH=`ps -efw | grep bacula-fd.conf | head -1 | awk '{
  for(i=1;i<=NF;i++)
  {
    if ($i ~ /bacula-fd.conf/)
    {
      print $i
    }
  }
}'`
  if [ -f $CONFPATH ]; then
    echo $CONFPATH
  else
    echo ${srcdir}/src/filed/bacula-fd.conf
  fi
}

# Copy conf file if not already loaded
if test ! -f bin/bacula-fd.conf ; then
   cp -f `find_config` bin/bacula-fd.conf
fi

if test -f ${srcdir}/src/filed/static-bacula-fd ; then
   echo " "
   echo "Found existing statically compiled file daemon, using it"
   echo " "
   cp -f ${srcdir}/src/filed/static-bacula-fd bin/bacula-fd
else
   cwd=`pwd`
   cd ${srcdir}
   echo "Compiling bacula source"
   make 2>/dev/null >/dev/null
   cd ${srcdir}/src/filed
   echo "Compiling static-bacula-fd"
   make static-bacula-fd 2>/dev/null >/dev/null
   if test $? -ne 0 ; then
      echo " "
      echo "Build of static-bacula-fd failed."
      echo "This is most likely because you did not do a ./configure"
      echo "before running this script, or your build includes some"
      echo "options such as TLS that require static libraries that"
      echo "not loaded on your system.  I'm going to try to run a simplifed"
      echo "./configure in your Bacula source directory.  Please take note"
      echo "that your original configuration will be left changed."
      echo " "
      cd ${srcdir}
      ./configure \
         --prefix=/tmp \
         --sbindir=/tmp \
         --sysconfdir=/tmp \
         --with-scriptdir=/tmp \
         --enable-smartalloc \
         --enable-client-only \
         --enable-static-fd  2>/dev/null >/dev/null
      make  2>/dev/null >/dev/null
      cd $cwd
      cp -f ${srcdir}/src/filed/static-bacula-fd bin/bacula-fd
      if test $? -ne 0 ; then
         echo " "
         echo "Build of static-bacula-fd failed. I give up."
      fi
   fi
   rm -f ${srcdir}/src/filed/static-bacula-fd
fi
