#!/bin/bash
# E.G : ./vlctest "enqueue tst.mp4" pause "seek 0" play

# Parse options 

h_set=0
#~ s_set=0
#~ d_set=0
while getopts "h:" OPT; do
  case "$OPT" in
    h)
      echo "Sending to ${OPTARG}"
      h_set=1
      ADDRESSES=("${OPTARG}")
      shift $((OPTIND-1))
      CMDS="$*"
      ;;
    #~ c)
      #~ c_set=1
      #~ CMDS=("${OPTARG}")
    #~ s) s_set=1;;
    #~ d) d_set=1;;
    *) # getopts produces error
       exit 1;;
  esac
done

# If no host provided, use all by default
#~ if ((!h_set && OPTIND>$#)) ; then
if ((!h_set)) ; then
  echo "Sending to all hosts"
  # RPIs wlan adresses
  ADDRESSES=("10.42.0.1" "10.42.0.135" "10.42.0.142")
  CMDS="$*"
  echo ${ADDRESSES[@]}
fi
# Split str into args 
readarray -d "+" -t CMDAR <<< "$CMDS"
echo ${CMDAR[@]}

# Telnet password
PASSWD="secret"

# Send commands
for ADDR in ${ADDRESSES[@]}
do
    echo "Sending command $1 and $2 to $ADDR..."
    echo -e "$PASSWD\n${CMDAR[0]}\n${CMDAR[1]}" | nc "$ADDR" 9999 -w 5 &
    #~ echo -e "$PASSWD\n$1\n$2" | nc "$ADDR" 9999 -w 5 &
#    echo -e "$PASSWD\n$1\n$2" | nc "$ADDR" 9999 -w 5 | sed '/Welcome/d;/VLC/d;/Password/d;' &
#    echo -e "$PASSWD\n$1\n$2" | nc "$ADDR" 9999 > /dev/null &
done
sleep 1
for ADDR in ${ADDRESSES[@]}
do
    echo "Sending command ${CMDAR[2]} and ${CMDAR[3]} to $ADDR..."
    echo -e "$PASSWD\n${CMDAR[2]}\n${CMDAR[3]}" | nc "$ADDR" 9999 > /dev/null &
    #~ echo "Sending command $3 and $4} to $ADDR..."
    #~ echo -e "$PASSWD\n$2\n$4" | nc "$ADDR" 9999 > /dev/null &
done