#!/bin/bash

. /usr/lib/eole/diagnose.sh


eKO() {
  EchoRouge "Erreur"
}

eOK() {
  EchoVert "Ok"
}

one()
{
  su oneadmin -s /bin/sh -c "$@"
}

TestServiceStatus() {
  printf ".  %${len_pf}s => " "$1"
  /etc/init.d/$2 status >/dev/null 2>&1
  if [ $? -eq 0 ] ; then
    eOK
  else
    eKO
  fi
}

eOneStatus() {
    [ "$1" = "STOPPED" -o "$1" = "UNKNOWN" ] && EchoRouge "$1" && return
    [ "$1" = "ACTIVE" ] && EchoVert "$1" && return
    EchoOrange "$1"
}


EchoGras "*** Virtualisation"

if [ "$(CreoleGet 'activer_openvswitch')" != "oui" ]; then
    printf ".  %${len_pf}s => " "Virutalisation"
    EchoOrange "Non actif"
  fi

TestServiceStatus "libvirt" libvirt-bin
TestServiceStatus "OpenNebula" opennebula
TestService "XMLRPC" "localhost:2633"
TestService "Sunstone" $(CreoleGet "ip_sunstone"):$(CreoleGet "port_sunstone")
TestService "Proxy VNC" $(CreoleGet "ip_sunstone"):$(CreoleGet "vnc_proxy_port_sunstone")
if [ "$(CreoleGet 'activer_oneflow')" == 'oui' ]; then
TestService "OneFlow" $(CreoleGet "ip_oneflow"):$(CreoleGet "port_oneflow")
fi
echo ""
TestServiceStatus "OpenVswitch" openvswitch-switch
echo ""

if [[ $(CreoleGet activer_onesinglenode 2>&1) == 'oui' ]]
then
  EchoGras "*** Noeuds du cluster Hâpy"

  NODES=$(one 'onehost list -l ID,NAME,STAT' | awk '!/ID.*NAME.*STAT/ {print $1 ":" $2 ":" $3}')
  for elm in ${NODES}
  do
    node=(${elm//:/ })
    id=${node[0]}
    name=${node[1]}
    state=${node[2]}

    printf ".  %${len_pf}s => " "$name"
    eOneStatus "${state}"
  done
fi

EchoGras "*** Machines Virtuelles"

# Les machines virtuelles se terminant par -TEST ne sont pas vérifiées
VMs=$( one 'onevm list -l ID,NAME,STAT'  | tail -n +2 | grep -ve '\-TEST ' | awk '{print $1}' )
if [[ -z ${VMs} ]]
then
  printf ".  %${len_pf}s " "Pas de machines virtuelles instanciées"
else
  for VM in $VMs ; do
    NAME=$( one "onevm show $VM" | grep 'NAME' | cut -d: -f2 )
    STAT=$(one "onevm show $VM" | grep '^STATE'  | cut -d: -f2 | tr -d ' ' )
    printf ".  %${len_pf}s => " "$NAME"
    eOneStatus "$STAT"
  done
fi

echo ""