#!/bin/bash

# Proxmox VE virtual machine listing
# (c) 2015-2019, Tom Laermans for Observium

PVESH=`which pvesh`
if [ $? -eq 0 ]
then
  echo "<<<proxmox-qemu>>>"

  VERSION=$(pveversion | awk -F/ '{print $2}' | sed 's/\..*//')
  if [[ ${VERSION} -ge 5 ]]
  then
    JSON=`pvesh get /nodes/$(hostname)/qemu --output-format=json-pretty 2>/dev/null`
  else
    pvesh get /nodes/$(hostname)/qemu 2>/dev/null
  fi
fi

count=`echo $JSON | jq '. | length' `
CACHE="/usr/lib/observium_agent/scripts-enabled/cached"
touch $CACHE

#for ((i=$count-1; i>=0; i--)); do
#       JSON=`echo $JSON | jq 'del(.['$i']|select(.["name"] | startswith("VM ")))'`
#       JSON=`echo $JSON | jq 'del(.['$i']|select(.["name"] | startswith("veeam-")))'`
#done
#last=$(($count-1))

JSON=`echo $JSON | jq 'del(.[]|select(.["name"] | startswith("VM ")))'`
JSON=`echo $JSON | jq 'del(.[]|select(.["name"] | startswith("veeam")))'`
count=`echo $JSON | jq '. | length' `

for ((i=0; i<$count; i++)); do
    name=`echo $JSON | jq -r '.['$i'].name'`
    vmid=`echo $JSON | jq -r '.['$i'].vmid'`

    #if [[ ! $name =~ $ignoRE ]]; then
        exec 2>/dev/null
        var1=`qm guest cmd ${vmid} get-osinfo | jq -r '.["pretty-name"]'`
        var2=`cat ${CACHE} | grep ${vmid} | awk -F':' '{print $2}'`
        var3=`cat /etc/pve/qemu-server/${vmid}.conf | grep -m 1 ostype | awk '{print $2}'`
    
        ostype=$var1
        if [[ -z "$ostype" || "$ostype" == *"is not running"* || "$ostype" == *"QEMU guest agent configured"* ]]; then
                ostype=$var2
                if [[ -z "$ostype" ]]; then
                        ostype="$var3 (more precise information not yet available)"
                fi
        else
                sed -i "s|$vmid:.*|$vmid:$var1|" $CACHE
        fi

        if [[ -z "$var2" ]]; then
            grep $vmid $CACHE > /dev/null
            if [ "$?" == "1" ]; then
                    echo "$vmid:" >> $CACHE
            fi
        fi

        if [ "$i" == "0" ]
        then
            CMD=".[$i] += {\"os\":\"$ostype\"}"
        else
            CMD=$CMD" | .[$i] += {\"os\":\"$ostype\"}"
        fi
        #echo "$name is $vmid # $var1 ## $var2 ### $var3" ; echo "---"
    #fi
done

jqcmd=(jq "$CMD")

#echo run it now
echo "$JSON" | "${jqcmd[@]}"

