#!/bin/bash

if [ $# -eq 0 ]; then
  echo "usage $0 host"
  exit 1
fi

# Define the path and any password options for MPD
MY_MPC="/usr/bin/mpc -h $1"

while [ 1 ]; do
  # Check if the server is up and running
  ping -c 2 -W 1 $1 2>&1>/dev/null
  if [ $? -eq 0 ]; then
    echo "$1 is alive..."
    # Check if MPD is up and running
    $MY_MPC status
    if [ $? -eq 0 ]; then
      echo "MPD is running..."
      # We're alive, so let's play
      # First let's see how many tracks are in the playlist
      number_of_tracks=`$MY_MPC playlist | wc -l`
      # If we have less than 2 tracks playing, add random(s)
      # Why 2? Well it ensures no break in the music
      if [ $number_of_tracks -lt 2 ]; then
        echo "Adding tracks..."
        # How many tracks needed?
        number_to_add=`expr 2 - $number_of_tracks`
        random_tracks=`cat /tmp/random_mpd_tracks.txt | shuf -n $number_to_add`
        # Add it to the play list
        $MY_MPC add $random_tracks
      fi
      # Set up the playing style
      $MY_MPC -q single off
      $MY_MPC -q random off
      $MY_MPC -q repeat off
      $MY_MPC -q consume on
      # Press "play" :-)
      $MY_MPC -q play
    fi
  fi
  sleep 10
done

