#!/bin/bash
set -euo pipefail

COLOR_RED='\033[1;31m'
COLOR_DEFAULT='\033[0m'

function safe_cmd() {
  # Pgrep finds itself as one of the matches so when it returns
  # each PIDs on a newlines, this checks for more than 1 match

  zcore_running=1
  process_count=1 # this script counts as 1

  # Don't ssh if we're on main-ai. Doing so increases the process count.
  if [[ $(hostname) =~ "drc-" ]] || [[ $(hostname) =~ "kitt" ]]; then
   zcore_running=`pgrep -f "zcore" | wc -l` # subprocess here counts as 1
   process_count=2
  else
   # subprocess does not count due to ssh
   zcore_running=`ssh main-ai 'pgrep -f "zcore" | wc -l'`
  fi

  if [ $((zcore_running)) -ne $process_count ]
    then
    echo -e "${COLOR_RED}Command could not execute because zcore is running.${COLOR_DEFAULT}"
    exit 126;
  fi

  cd "${HOME}/driving"
  "$@"
}

safe_cmd "$@"
