#!/bin/bash

if [ $(CreoleGet activer_nut) = "oui" ]; then
    if [ $(CreoleGet nut_ups_daemon) = "oui" ]; then
        for nut_ups_name in $(CreoleGet nut_ups_name); do
            monitors="$monitors$nut_ups_name@localhost "
        done
    else
        NAME=($(CreoleGet nut_monitor_foreign_name))
        HOST=($(CreoleGet nut_monitor_foreign_host))
        for IDX in $(seq 0 $((${#NAME[@]} - 1))); do
            name=${NAME[$IDX]}
            host=${HOST[$IDX]}
            monitors="$monitors$name@$host "
        done
    fi
    . /usr/lib/eole/diagnose.sh
    EchoGras "*** Onduleur"
    for monitor in $monitors; do
        printf ".  %${len_pf}s => " $monitor
        status=$(/bin/upsc $monitor ups.status 2> /dev/null)
        if [ $? -ne 0 ];then
            status=$(/bin/upsc $monitor ups.status 2>&1 | grep -v 'Init SSL without certificate database')
            EchoRouge "$status"
        else
            charge=`/bin/upsc $monitor battery.charge 2> /dev/null| cut -d'.' -f1`
            #si OL dans le status
            for a in $status; do
                [ "$a" = "OL" ] && ok=true
                if [ "$a" = "ALARM" ]
                then
                    ok=false
                    alarm=$(/bin/upsc $monitor ups.alarm 2>&1)
                    if [ $? -ne 0 ]
                    then
                        alarm="Type d'alarme inconnue"
                    else
                        alarm=$(sed -e 's/Init SSL without certificate database//g' <<< $alarm)
                    fi
                    break
                fi
            done

            if [ "$ok" = "true" ]; then
                EchoVert "OK ($charge%)"
            elif [ "$ok" = "false" ]; then
                EchoRouge "$alarm"
            elif [ "$charge" -lt "20" ]; then
                EchoRouge "Charge batterie faible ($charge%)"
            else
                EchoOrange "Fonctionnement sur batterie ($charge%)"
            fi
        fi
    done
    echo
fi
