#!/bin/sh

# Export the sandbox exit code for later use
exit_with_code() {
  echo $1 > $HOME/sandboxes/$PWD/exitcode
  exit $1
}

if [ $(uname) == "FreeBSD" ]; then
  # Use FreeBSD jails
  HOME=$HOME $HOME/services/sandbox_freebsd $*
  exit_with_code $?
else
  # Use bubblewrap and Nix package manager on Linux
  if [ -e $HOME/bws_skip_nixpkgs ]; then                                                                                  
    HOME=$HOME $HOME/services/sandbox_linux $*                                                                                            
    exit_with_code $?
  fi 

  # Add support for nix-shell if available
  if [ -e "shell.nix" ] && which nix-shell; then
    echo Loading Nix packages
    nix-shell --run "HOME=$HOME $HOME/services/sandbox_linux $*"
  elif [ -e "nix.packages" ] && which nix-shell; then
    echo Loading Nix packages
    nix-shell -p $(xargs -a nix.packages echo) --run "HOME=$HOME $HOME/services/sandbox_linux $*"
  elif [ -e "packages.nix" ] && which nix-shell; then
    echo Loading Nix packages
    nix-shell -p $(xargs -a packages.nix echo) --run "HOME=$HOME $HOME/services/sandbox_linux $*"
  else
    HOME=$HOME $HOME/services/sandbox_linux $*
  fi
fi

exit_with_code $?
