#!/usr/bin/env python3
# Copyright (c) 2007-2011 Arista Networks, Inc.  All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.
#!/usr/bin/python

import time, os, optparse # pylint: disable=deprecated-module
voltages = ["low", "nominal", "high"]

parser = optparse.OptionParser()
parser.usage = "%prog [ OPTIONS ]"
parser.add_option( "-o", action="store", type="str", default="/var/log/voltage",
                   help="log file (default: %default)" )
parser.add_option( "-i", action="store", type="int", default=30*60,
                   help="interval in seconds (default: %default )" )
parser.add_option( "--test", action="store_true",
                   help="test the script, but don't actually margin voltage" )
parser.add_option( "-v", action="store", type="str", default="low,high",
                   help="comma-separated list of voltages from the set "
                   "{low,nominal,high}(default: %default )" )

( options, args ) = parser.parse_args()
if args:
   parser.error( "Unexpected arguments:" + " ".join(args) )

voltages = options.v.split( "," )
for v in voltages:
   if v not in ["low", "nominal", "high"]:
      # pylint: disable-next=consider-using-f-string
      parser.error( "unexpected voltage '%s'" % v )

logfile = options.o

failed = False
def log(logmsg):
   global failed
   stime = time.strftime( "%X %x %Z" )
   try:
      # pylint: disable-next=consider-using-with
      open( logfile,"a" ).write( stime + ": " + logmsg + "\n" )
      failed = False
   except:                                 # pylint: disable-msg=W0702
      if not failed:
         print( f"{stime}: failed to write log file '{logfile}'" )
         failed = True
   print( f"{stime}: {logmsg}" )

# pylint: disable-next=consider-using-f-string
log( "starting voltage margining loop voltages: %s interval: %s" %
     (options.v, options.i) )

import Tac # pylint: disable=wrong-import-position
while True:
   for v in voltages:
      # pylint: disable-next=consider-using-f-string
      log( "margining voltage to %s" % (v) )
      cmd = "lock_volts -g all -m %s" % v  # pylint: disable=consider-using-f-string
      if options.test:
         print( cmd )
      else:
         os.system( cmd )
      Tac.runActivities(options.i)

