#! /bin/bash

if [[ $EUID -ne 0 ]]; then
  echo "ERR: mps must be run as root";
  exit 1;
fi

case "$1" in
  start)
    if [ "$(pidof mpsd)" ]; then
      echo "ERR: mpsd already running (PID: $(pidof mpsd))";
    else
      if [ -f /update/mps_update.tar.gz ]; then
        tar --overwrite -xf /update/mps_update.tar.gz -C /usr/bin/ > /dev/zero 2>&1;
        chmod +x /usr/bin/mps* > /dev/zero 2>&1;
        rm /update/mps_update.tar.gz > /dev/zero 2>&1;
      fi
      mpsd -d& > /dev/zero 2>&1;
      sleep 1;
      echo "OK: mpsd started";
    fi
    ;;
  stop)
    if [ "$(pidof mpsd)" ]; then
      killall -9 mpsd > /dev/zero 2>&1;
      sleep 2;
      echo "OK: mpsd stopped";
    else
      echo "ERR: mpsd is not running";
    fi
    ;;
  restart)
    $0 stop;
    $0 start;
    ;;
  check)
    if [ "$(pidof mpsd)" ]; then
      echo "OK: mpsd is running (PID: $(pidof mpsd))";
    else
      echo "OK: mpsd is not running";
    fi
    ;;
  *)
    echo "ERR: Usage $0 {check|start|stop|restart}";
    ;;
esac

exit 0;
