#!/bin/bash
# ------------------------------------------------------------------
# [DADT@IFPE] script_bacula-job-discover
#          Script utilizado pelo Zabbix para obter propriedades dos
#          dos jobs de backup do Bareos/Bacula
# ------------------------------------------------------------------

# HISTORY
#     2019/05/09 : xxxxxxxxxxxxxx : Versão inicial do script
#     2015/10/14 : Paulo Fernando : Pequenos melhoramentos no código

VERSION=0.1.0
USAGE="
Usage:
Run "./"$0 with no argument, to return all jobs.
Run "./"$0 <level> to return jobs with that level. Can be \"Full\", \"Incr\" or \"Diff\".
\n"

# --- Options processing -------------------------------------------
if [ $# == 0 ] ; then
    printf "$USAGE"
    exit 1;
fi

# ------------------------------------------------------------------

file="/tmp/jobs_discovery_lld.txt"

filterJob=""
Bconsole="$(which bconsole)"
Grep="$(which grep)"
Sed="$(which sed)"


get_jobs()
{
    until [ -z "$1" ]
    do
      if [ ${1:0} != 'Job:' ]
      then
          tmp=${1:0}               
          parameter=${tmp%%=*}     
          value=${tmp##*=}
          eval $parameter=$value

          if [ $parameter == 'Level' ]
          then
              if [ -z $lastLevel ]
              then
                  lastLevel=$Level
                  Level=$Level
              else
                  Level=$lastLevel,$Level
                  lastLevel=$Level
              fi
          fi
      fi
      shift
    done

    if [ ! -z $name ] && [ $Enabled == '1' ]
    then

      case "$filterJob"
      in
        "") 
           echo $name
           ;;
        *) 
           if [[ ${Level} =~ ${filterJob} ]]
           then
              echo $name
           fi
           ;;
      esac

    fi

    lastLevel=""
}

## GENERATE AUTO DISCOVERY JSON
generate_json()
{
  echo -e "{" > $file
  echo -e "\t\"data\":[" >> $file
  first=1
  for i in $*
  do
    if [ $first == 0 ]
    then
      echo -e "\t," >> $file
    fi
    first=0
    echo -e "\t{\"{#JOB}\":\"$i\"}" >> $file
  done
  echo -e "\t]" >> $file
  echo -e "}" >> $file
}

## EXECUTION

if [ -z "$1" ]
then
  # Sem argumentos, descobre todos os jobs
  generate_json \
  $(echo "show job"| $Bconsole | $Grep "Job:" | while read LINE; do get_jobs $LINE; done)
else

  export filterJob="$1"
  export $1=""

  # Com argumentos filtra os jobs por tipo
  generate_json \
  $(echo "show job"| $Bconsole | awk '/Job:/,/--> Messages/' |$Grep 'Job:\|Level=' | $Sed 's/ --> Run //g' | tr -d '\n' | $Sed 's/Job:/\nJob:/g' | while read LINE; do get_jobs $LINE; done)

fi

cat $file
rm -f $file
