#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Check Research Node Status
# Copyright (C) 2013-2024 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: dreibh@simula.no

import sys

# NorNet
from NorNetTools import *
from NorNetAPI   import *


# ###### Main program #######################################################
if len(sys.argv) != 2:
   error('Usage: ' + sys.argv[0] + ' [VM_name]')
vmName = sys.argv[1]

try:
   loginToPLC(quietMode=True)

   nodeList = getPLCServer().GetNodes(getPLCAuthentication(), 
                 { 'hostname' : vmName },
                 [ 'hostname', 'boot_state', 'run_level' ])

   if len(nodeList) > 0:
      node = nodeList[0]
      if ((node['boot_state'] == 'boot') and
          (node['run_level'] == 'failboot')):
         print(vmName + ' has boot failure')
         sys.exit(1)
      elif (node['boot_state'] == 'reinstall'):
         print(vmName + ' needs a reinstall')
         sys.exit(1)

except Exception as e:
   print('Cannot determine the state of ' + vmName + ': ' + str(e))
