#!/usr/bin/env bash
# this script is executed by multiple buildkite agents running on one node, so we write the pid to a file
# if the pidfile exists we know another process is executing so we don't need to install anything
#
# A more robust approach would be to use a lock file, but that would require some more work
set -eu
pushd "$(dirname "${BASH_SOURCE[0]}")"/../..

WORKDIR=$(pwd)
PIDFILE=/var/lock/dobackup.pid

remove_pidfile()
{
  rm -f "$PIDFILE"
}

another_instance()
{
  echo "There is another instance running, skipping"
  exit 0
}

if [ -f "$PIDFILE" ]; then
  kill -0 "$(cat $PIDFILE)" && another_instance
fi
trap remove_pidfile EXIT
echo $$ > "$PIDFILE"

echo "Installing asdf dependencies as defined in '${WORKDIR}/.tool-versions':"
if [ ! -f ".use_mise" ]; then
  asdf install
else
  mise install
  eval "$(mise activate)"
fi
