#!/bin/bash
#####################################################################
#                                                                   #
#  Starts the cava audio data stream and saves it to cava-out.tmp   #
#                                                                   #
#  Scripted by Koentje  (remon@cobrasoft.nl)                        #
#                                                      version 2.6  #
#####################################################################

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

# Check if independencies are installed
  if [ "$(which cava)" = "" ]; then echo -e "\e[31mERROR\e[m 'cava' not installed!  (see README.TXT for more info)\n"; exit 1; fi

# Check if cava and conky are already running, if so then exit script
  icava=$(pgrep -lx cava)
  iconky=$(wmctrl -l | grep -w 'conky-musicplayer-VU' | awk '{print $NF}')
  if [ "$icava" != "" ] && [ "$iconky" != "" ]; then
    echo -e "\e[33mWARN\e[m  [vu-cava-loop] Cava and Conky already running, exit script!" >/dev/stderr
    exit 1
  elif [ "$icava" != "" ] && [ "$iconky" = "" ]; then
    echo -e "\e[33mWARN\e[m  [vu-cava-loop] Cava is running without conky, killing cava datastream!" >/dev/stderr
    killall cava
    exit 1
  fi



# Terminate
function terminate () {
  echo -e "\e[33mWARN\e[m  [vu-cava-loop] Conky VU-meters not running, killing cava datastream!"  >/dev/stderr
  ./stop
  exit 1
}



# Set loop to check if conky is still running, if not then kill cava and exit script
function conky_active () {
  sleep 2
  cnt=1
  iconky=$(wmctrl -l | grep -w 'conky-musicplayer-VU')
  # search for conky window at least 5 times before we exit
  while [ "$iconky" = "" ]
  do
     sleep 1
     iconky=$(wmctrl -l | grep -w 'conky-musicplayer-VU')
     echo -e "\e[33mWARN\e[m  [vu-cava-loop] Conky VU-meters not found!  (Retry $cnt)"  >/dev/stderr
     if [ "$cnt" = "5" ]; then
        terminate
        exit 1
     fi
     cnt=$((cnt+1))
  done
  conky_active
}
conky_active &



# Saves last line from cava stream to tmp file
  echo -e "\e[32mINFO\e[m  [vu-cava-loop] Cava datastream is running." >/dev/stderr
  while read -r  line
  do
     echo $line > ./tempfiles/cava-out.tmp
  done < <(cava -p ./vu-cava-config)
  echo -e "\e[32mINFO\e[m  [vu-cava-loop] Exit cava datastream!" >/dev/stderr

