#!/bin/bash
# which program has been called?

CMD=${0##*/m}
MCDIR=$(dirname $0)

PROCSTRING="${MCDIR}/mclient.py $CMD"
FOUND=$(ps -ef | grep "$PROCSTRING" | grep -v grep)

if [[ ! -z $FOUND ]]; then
    echo "Already running: $FOUND"
    exit 1
fi

test_py(){
  typeset py=$1
  pypath=$( which $py 2>/dev/null )
  if [[ $? -ne 0 ]]; then
    return 1
  fi

  $pypath -c "import mars.utils" >/dev/null 2>&1
  if [[ $? -eq 0 ]]; then
    return 0
  else
    return 1
  fi
}

# try to figure if python salt modules are installed for python3 and/or python2
test_py 'python3'
py3=$?

test_py 'python'
py2=$?

if [[ $py3 -eq 0 ]]; then
  pyver=3
elif [[ $py2 -eq 0 ]]; then
  pyver=2
else
  echo "No python interpreter found => Exiting"
  exit 1
fi

case $pyver in
  2) timeout -k 60 -s KILL 7200 python "${MCDIR}"/mclient.py "$CMD" 2>/dev/null;;
  3) timeout -k 60 -s KILL 7200 python3 "${MCDIR}"/mclient.py "$CMD" 2>/dev/null;;
  *) echo "Couldn't find installed salt python modules - exiting"
     exit 1;;
esac