#!/bin/sh

# MQTT Shell Listen & Exec
host=$2
clean="output input cmds";p="backpipe";pid=$(cat pidfile)
ctrl_c() {
  echo "Cleaning up..."
  rm -f $p;rm "$clean";kill $pid 2>/dev/null
  if [[ "$?" -eq "0" ]];
  then
     echo "Exit success";exit 0
  else
     exit 1
  fi
}

listen(){
([ ! -p "$p" ]) && mkfifo $p
(mosquitto_sub -h $host -t input >$p 2>/dev/null) &
echo "$!" > pidfile
while read line <$p
do
  echo $line > cmds
  if grep -q "quit" cmds; then
    (rm -f $p;rm $clean;kill $pid) 2>/dev/null
    break
  else
    (bash cmds | tee out) && mosquitto_pub -h $host -t output -f out;>out
  fi
done
}

usage(){
echo "    Mqtt-Exec Listener Via Bash"
echo "  Usage: $0 <mqtt server>"
echo "  Subscripe to topic \"output\", publish to topic \"input\""
}

case "$1" in
-h|--host)
trap ctrl_c INT
listen
;;
*)
usage
exit 1
;;
esac

