#!/usr/bin/env python3
# Copyright (c) 2008 Arastra, Inc.  All rights reserved.
# Arastra, Inc. Confidential and Proprietary.

""" Checks the voltage of the rtc battery. The expected voltage is around
3V. We declare success is the voltage is between 3V - 10% and 3V + 20%. """
from __future__ import absolute_import, division, print_function

import Tac, optparse, EntityManager, sys # pylint: disable=deprecated-module
parser = optparse.OptionParser()
parser.add_option( "-s", "--sysname", action="store",
                   help="System name (default: %default)",
                   default="ar" )
parser.add_option( "", "--cell", action="store", type=int,
                   help="System cell id (default is current cell id)" )
( options, args ) = parser.parse_args()

if args:
   parser.error( "unexpected arguments" )

cellId = options.cell
if not cellId:
   import Cell
   cellId = Cell.cellId()

em = EntityManager.Sysdb( sysname=options.sysname )

# Mount the hardware rtc state
mg1 = em.mountGroup()
mg1.mount( 'hardware/cell', 'Tac::Dir', 'r' )
mg1.close( blocking=True )
mg2 = em.mountGroup()
# pylint: disable-next=consider-using-f-string
mg2.mount( 'hardware/cell/%d' % cellId, 'Tac::Dir', 'r' )
mg2.close( blocking=True )
mg3 = em.mountGroup()
# pylint: disable-next=consider-using-f-string
rtc = mg3.mount( 'hardware/cell/%d/rtc' % cellId, 'Hardware::Rtc', 'r' )
mg3.close( blocking=True )

sensorStatus = rtc.voltageSensorStatus
if not sensorStatus:
   print( "Checking the voltage on the rtc not supported on this system" )
   sys.exit( 0 )

Tac.waitFor( lambda: sensorStatus.hwStatus == "ok",
             timeout=120,
             description="sensor to be initialized" )

Tac.waitFor( lambda: repr( sensorStatus.voltage ) != "nan",
             timeout=120,
             description="sensor value to be read" )
voltage = sensorStatus.voltage
print( "Rtc battery voltage is", voltage )

expectedVoltage = 3.0

if voltage < expectedVoltage * 0.9:
   print( "Rtc battery voltage is lower than required." )
   sys.exit( 1 )
elif voltage > expectedVoltage * 1.2:
   print( "Rtc battery voltage is higher than required." )
   sys.exit( 1 )
else:
   print( "Rtc battery voltage is ok")
   sys.exit( 0 )
