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

import time, os, optparse
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"]:
      parser.error( "unexpected voltage '%s'" % v )

logfile = options.o

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

log( "starting voltage margining loop voltages: %s interval: %s" %
     (options.v, options.i) )

import Tac
while True:
   for v in voltages:
      log( "margining voltage to %s" % (v) )
      cmd = "lock_volts -g all -m %s" % v 
      if options.test:
         print cmd
      else:
         os.system( cmd )
      Tac.runActivities(options.i)

