#!/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

# try to figure if python salt modules are installed for python3 and/or python2
pyver=$( salt-call -V | sed 's/ //g' | awk -F: '$1 ~ /Python/ {print $2}' | cut -c 1 )

case $pyver in
  2) python -c "import salt.client" > /dev/null 2>&1
     timeout -k 60 -s KILL 7200 python ${MCDIR}/mclient.py $CMD 2>/dev/null;;
  3) python3 -c "import salt.client" > /dev/null 2>&1
     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