#!/usr/pythoncontroller/python 

import sys, os, time, datetime
import devhealth

# to be called from cron to update and cache the devhealth status
# kvm crontab location: ramdisk-hv/builder/centos6/kvm/overlay/etc/crontab

smartpathprefix = '/tmp/smartinfo'# prefix of cached smart info filename
smartpathsuff = 'cache'		# suffix

def usage(cmd):
    print "Usage: %s [device name]\n" % cmd
    print "Updates devhealth information for all devices in the local system, or specific device if argument is provided."
    print "Output data is stored in files under path %s.*.%s" % (smartpathprefix, smartpathsuff)
    sys.exit()

def update_cache_for_device(device):

    if device:
	if device.startswith('/dev/'):
	    basedevname = device.strip().replace('/dev/','')
	else:
	    basedevname = device
	    device = '/dev/' + device
    else:
	basedevname = 'all'
	device = ''

    if basedevname.count('/') != 0: # check basedevname for /
	print("ERROR: invalid device argument! Exiting...")
	sys.exit(-1)
    
    foundevs = []
    testtypes = ['xerrors', 'health', 'attrib']

    for devtest in testtypes:

	error = False
	scfname = "%s.%s.%s.%s" % (smartpathprefix, basedevname, devtest, smartpathsuff)
	try:
	    if os.path.exists(scfname) and os.path.isfile(scfname):
		os.unlink(scfname) # delete older file

	    cf = open(scfname,'w')

	    cf.write( "updatetime=%d\n" % int(time.time()) )

	    hdicts = devhealth.getSmartDevHealthDicts(devtest,device,devtype)
	    cf.write( "%s\n" % str(hdicts) )

	    foundevs = [ d['device'] for d in hdicts ]

        except Exception, e:
	    print "Error in test %s, device %s" % (devtest, device)
	    error = True
        finally:
	    if cf:
		cf.close()

	if error and os.path.exists(scfname) and os.path.isfile(scfname):
	    os.unlink(scfname) # delete older file
        else:
	    print "Done with test %s, device %s -> file: %s" % (devtest, basedevname, scfname)

    return foundevs

""" ================================================================================== """

device = ''
devtype = ''
print "START - %s" % datetime.datetime.now().isoformat()
if len(sys.argv) == 2:
    # ok, do it for one device only...
    device = sys.argv[1]
    dd = update_cache_for_device(device)
    assert(len(dd) == 1)

elif len(sys.argv) > 2:
    usage(sys.argv[0])

else:
    # ok, need all devs in the system, together and separately...
    ddevs = update_cache_for_device(device)

    # and now separately
    for dev in ddevs:
	dd = update_cache_for_device(dev)
	assert(len(dd) == 1)

print "DONE - %s" % datetime.datetime.now().isoformat()
