#!/bin/bash
#
# Simple  script  to  activate  swipl from  the  current  cmake  build
# directory by linking  it from $HOME/.local/bin or  $HOME/bin. May be
# called as  below to activate a  version that was installed  from the
# current directory using the command below:
#
#     swipl-activate --installed
#
# This can be combined by setting the following in ~/.bashrc, which will
# install each configuration into a different directory.
#
#     export SWIPL_INSTALL_PREFIX=$HOME/cmake/swipl/@builddir@

swipl=
swiplwin=
swiplld=

dir-in-path()
{ arr=$(echo $PATH | tr ":" "\n")
  for x in $arr; do
      if [ "$x" = "$1" ]; then
	  return 0	
      fi
  done
  return 1
}

if [ -d $HOME/.local/bin ] && dir-in-path $HOME/.local/bin; then
    bindir=$HOME/.local/bin
elif [ -d $HOME/bin ] && dir-in-path $HOME/bin; then
    bindir=$HOME/bin
else
    echo "ERROR: Cannot find personal bin directory."
    exit 1
fi


if [ "$1" = "--installed" ]; then

  prefix=$(grep CMAKE_INSTALL_PREFIX:STRING= CMakeCache.txt | sed 's/.*=//')
  if [ -x $prefix/bin/swipl ]; then
    swipl=$prefix/bin/swipl
    if [ -x $prefix/bin/swipl-win ]; then
      swiplwin=$prefix/bin/swipl-win
    fi
    if [ -x $prefix/bin/swipl-ld ]; then
      swiplld=$prefix/bin/swipl-ld
    fi
  else
    echo "Cannot find swipl in $prefix/bin"
    exit 1
  fi

else

  if [ -x src/swipl ]; then
      swipl=$(pwd)/src/swipl
      if [ -x src/swipl-ld ]; then
	  swiplld=$(pwd)/src/swipl-ld
      fi
      if [ -x src/swipl-win ]; then
	  swiplwin=$(pwd)/src/swipl-win
      elif [ -x packages/swipl-win/swipl-win ]; then
	  swiplwin=$(pwd)/packages/swipl-win/swipl-win
      fi
  else
      echo "Please run from Cmake build directory"
      exit 1
  fi

fi

echo "Personal bin directory: $bindir"
echo "Activating $swipl"

rm -f $bindir/swipl
(cd $bindir && ln -s $swipl)
if [ ! -z "$swiplld" ]; then
  echo "       and $swiplld"
  rm -f $bindir/swipl-ld
  (cd $bindir && ln -s $swiplld)
fi
if [ ! -z "$swiplwin" ]; then
  echo "       and $swiplwin"
  rm -f $bindir/swipl-win
  (cd $bindir && ln -s $swiplwin)
fi

if [ ! -z "$SWI_HOME_DIR" ]; then
    var=SWI_HOME_DIR
    value="$SWI_HOME_DIR"
elif [ ! -z "$SWIPL" ]; then
    var=SWIPL
    value="$SWIPL"
fi

if [ ! -z "$var" ]; then
cat <<EOF

WARNING: The environment variable \$$var sets the "home" directory of
WARNING: SWI-Prolog to $value.  Please delete this variable to run the
WARNING: activated version of SWI-Prolog or set the value explicitly
WARNING: to $($swipl --home)
EOF
fi
