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

# This little script is alex.ho's super-cool cylon-raider led script
# using alex.rose's super-cool led fading support.  It probably
# belongs somewhere other than Diags (probably Arsys), but for now it
# lives here.

import time, sys
import Pci, ScdRegisters, optparse # pylint: disable=deprecated-module

numLed = 48
base = 0

GREEN_ON = 1
GREEN_OFF = 0
RED_ON = 1
RED_OFF =  0

scd = ScdRegisters.scdPciResourceFile()
if not scd:
   print( "No scd device found on this machine" )
   sys.exit(1)

def led( led, green, red ): # pylint: disable=redefined-outer-name
   assert( 0 <= led < numLed) # pylint: disable=superfluous-parens

   address = 0x60d0 + led * 0x10
   data = 0x0006ff00 | (green << 28) | (red << 27)

   Pci.MmapResource( scd ).write32( address, data )

def whichLed( counter ): # pylint: disable=redefined-outer-name
   value = counter % ((numLed * 2) - 2)
   if value >= numLed:
      value = (2 * numLed) - 2 - value
   return value + base

usage = "%prog [color] [-n numleds] [-d delay]"
parser = optparse.OptionParser(usage=usage)
parser.add_option( "-n", "--numleds", help="How many leds to light up", 
                   default=48, type=int )
parser.add_option( "-b", "--base", help="Which LED to start on", 
                   default=0, type=int )
parser.add_option( "-d", "--delay", help="How long to delay between lights", 
                   default=.2, type=float )

options,args = parser.parse_args()
if len( args ) > 1:
   parser.error( "too many arguments" )

color = args and args[0] or "green" # pylint: disable=consider-using-ternary
if not color in ["green","red"]:
   print( "unknown colour:", color )
   sys.exit(1)

numLed = options.numleds

if numLed > 48:
   parser.error( "I only handle 48 leds.  You probably are doing something silly." )

base = options.base

def lightup( current, color ): # pylint: disable=redefined-outer-name
   # pylint: disable-next=multiple-statements
   if color == "green": led ( current, GREEN_ON, RED_OFF )
   else: led ( current, GREEN_OFF, RED_ON ) 

counter = 0
while True:
   current = whichLed( counter )
   led ( current, GREEN_OFF, RED_OFF )
   counter += 1
   current = whichLed( counter )
   lightup( current, color )
   time.sleep( options.delay )

