#!/bin/bash
#################################################################
#                                                               #
#  Starts the cava data stream and saves it to cava-output.     #
#  It also starts a check loop to see if spectrum-bass conky    #
#  is still running. If not running, then it terminates cava.   #
#                                                               #
#  Scripted by Koentje  (remon@cobrasoft.nl)                    #
#                                                  version 1.7  #
#################################################################

if [ "$1" != "gocava" ]; then
   echo -e "\n\e[31mERROR:\e[m cava-loop can not start outside of conky!\n"
   exit 1
fi

source ./settings.ini


# Terminate all
terminate() {
  echo -e "cava-loop.sh : Cava engine terminated" > /dev/stdout
  killall $(basename $0)
  killall cava
  exit 0
}


# Check if cava and conky are already running, if so then exit script
  icava=$(pgrep -lx cava)
  iconky=$(wmctrl -l | grep conky-spectrum | awk '{print $NF}')
  if [ "$icava" != "" ] && [ "$iconky" != "" ]; then
    # Exit because both are running already!
    exit 1
  elif [ "$icava" != "" ] && [ "$iconky" = "" ]; then
    # Terminate cava engine because spectrum conky is not running!
    terminate
  fi


# Set loop to check if spectrum conky is still running
# If not then kill cava engine and exit script
function conky_active () {
  sleep 5
  iconky=$(wmctrl -l | grep conky-spectrum)
  if [ "$iconky" = "" ]; then
    terminate
  fi
  conky_active
}
conky_active &


# Saves last line from cava data stream to tmp file
  echo "cava-loop.sh : Cava engine started" > /dev/stdout
  echo "cava-loop.sh : Output to $cavaout" > /dev/stdout
  while read -r  line
  do
     echo "$line" > "$cavaout"
  done< <(cava -p ./cava-config)
  terminate

exit 0
