#!/usr/bin/python3
# LAVA Info - Copyright 2021 LAVA Controls - Stephen Loeckle

import configparser
from flask import Flask, render_template, request
import inspect
import json
import lavalib
import os
import platform
import sqlite3
import traceback

def version():
    return '1.5.19'

app = Flask(__name__)

osplatform = platform.system().lower()

if osplatform == 'linux':
    lavaboxagentconfigfile = ('/etc/lavaboxagent/lavaboxagent.conf')
    lavacontrolsagentconfigfile = ('/etc/lavacontrols/lavacontrols.conf')
elif osplatform == 'windows':
    if not application_path:
        application_path = os.getcwd()
    lavaboxagentconfigfile = ('{}\\conf\\lavaboxagent.conf'.format(application_path))
    lavacontrolsagentconfigfile = ('{}\\conf\\lavacontrols.conf'.format(application_path))

@app.route('/')
def index():
    gotthefunc = inspect.stack()[0][3]
    hardwaredata = hardwareinfo('hostname','mac','localip','lavaip')
    startupdata = {}
    startupdata.update(hardwaredata)
    softwaredata = {}
    softwaredata = softwareversions()
    startupdata.update(softwaredata)
    msg = 'LAVA Box Starting Up...'
    try:
        if softwaredata['LAVA Controls Agent']['Installed'] :
            if softwaredata['LAVA Controls Agent']['Configured'] == False:
                msg = 'Device not configured or registered with the LAVA Controls platform. Please contact the service department at service@lavacontrols.com or +1-214-506-0300 option 2 and we will get you setup!'            
        if softwaredata['LAVA Box Agent']['Installed'] :
            if softwaredata['LAVA Box Agent']['Configured'] == False:
                msg = 'Device not configured or registered with the LAVA Controls platform. Please contact the service department at service@lavacontrols.com or +1-214-506-0300 option 2 and we will get you setup!'
    except:
        pass
        msg = ('Error in {}!'.format(gotthefunc))
        print(gotthefunc, msg, 40)
        err = traceback.format_exc()
        msg = ('Error in {} Detail: {}'.format(gotthefunc,err))
        print(gotthefunc, msg, 10)
        msg = ''
    
    return render_template('index.html', startupdata=startupdata,msg=msg)

@app.route('/hardware')
def hardware():
    gotthefunc = inspect.stack()[0][3]
    hardwaredata = hardwareinfo('all')
    format = request.args.get('show')
    if format == 'json':
        json_data = json.dumps(hardwaredata, indent = 4)
        return (json_data)
    else:
        return render_template('hardware.html', hardwaredata=hardwaredata)
    
def hardwareinfo(*options):
    gotthefunc = inspect.stack()[0][3]
    hardwaredata = {}
    if 'all' in options:
        options = ['mac','hostname','lavaip','localip','mem','ssd','cpu','cputemp','timezone']
    for o in options:
        if o == 'mac':
            try:
                mac = lavalib.boxinfo('mac')
            except:
                pass
                msg = ('Error in {}!'.format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Error in {} Detail: {}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
            else:
                hardwaredata['MAC Address'] = mac
        elif o == 'hostname':
            print('getting hostname')
            try:
                print(lavalib.boxinfo('h'))
                hostname = lavalib.boxinfo('h')
            except:
                pass
                msg = ('Error in {}!'.format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Error in {} Detail: {}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)                
            else:
                if hostname != "UNKNOWN":
                    hardwaredata['Host Name'] = hostname
                print(hostname)
        elif o == 'lavaip':
            try:
                lavaip = lavalib.boxinfo('lavaip')
            except:
                pass
                msg = ('Error in {}!'.format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Error in {} Detail: {}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)                
            else:
                if lavaip != "UNKNOWN":
                    hardwaredata['LAVA IP Address'] = lavaip
        elif o == 'localip':
            try:
                localip = lavalib.boxinfo('localip')
            except:
                pass
                msg = ('Error in {}!'.format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Error in {} Detail: {}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)                
            else:
                hardwaredata['LAN IP Address'] = localip
        elif o == 'mem':
            try:
                mem = lavalib.boxinfo('m')
            except:
                pass
                msg = ('Error in {}!'.format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Error in {} Detail: {}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)                
            else:
                hardwaredata['RAM Usage %'] = mem.percent
        elif o == 'ssd':
            try:
                ssd = lavalib.boxinfo('d')
            except:
                pass
                msg = ('Error in {}!'.format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Error in {} Detail: {}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)                
            else:
                hardwaredata['SSD Usage %'] = ssd.percent
        elif o == 'cpu':
            try:
                cpu = lavalib.boxinfo('c')
            except:
                pass
                msg = ('Error in {}!'.format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Error in {} Detail: {}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)                
            else:
                hardwaredata['CPU Usage %'] = cpu
        elif o == 'latency':
            try:
                latency = lavalib.boxinfo('l')
            except:
                pass
                msg = ('Error in {}!'.format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Error in {} Detail: {}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)                
            else:
                hardwaredata['Latency to 8.8.8.8'] = latency
        elif o == 'cputemp':
            try:
                cputemp = lavalib.boxinfo('c_temp')
            except:
                pass
                msg = ('Error in {}!'.format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Error in {} Detail: {}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)                
            else:
                hardwaredata['CPU Temperature'] = cputemp
        elif o == 'timezone':
            try:
                timezone = lavalib.boxinfo('timezone')
            except:
                pass
                msg = ('Error in {}!'.format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Error in {} Detail: {}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)                
            else:
                hardwaredata['Current Timezone'] = timezone
        
    return(hardwaredata)

@app.route('/software')
def software():
    gotthefunc = inspect.stack()[0][3]
    softwaredata = softwareversions()
    return render_template('software.html', softwaredata=softwaredata)
    
def softwareversions():
    lbatoken = None
    lcatoken = None
    softwaredata = {}
    softwaredata['LAVA Info'] = {}
    softwaredata['LAVA Info']['Version'] = version()
    try:
        import lavaconfiglib
    except:
        pass
    else:
        softwaredata['LAVA Config'] = {}
        softwaredata['LAVA Config']['Version'] = lavaconfiglib.version()
    softwaredata['LAVA Box Agent'] = {}
    try:
        import lavaboxagentlib
    except:
        softwaredata['LAVA Box Agent']['Installed'] = False
        pass
    else:
        softwaredata['LAVA Box Agent']['Installed'] = True
        softwaredata['LAVA Box Agent']['Version'] = lavaboxagentlib.version()
        config1 = configparser.ConfigParser()
        try:
            config1.read([lavaboxagentconfigfile])
        except:
            pass
        else:
            try:
                lbatoken = config1.get('system', 'token')
            except:
                pass
                softwaredata['LAVA Box Agent']['Configured'] = False
            else:
                if len(lbatoken) > 5:
                    softwaredata['LAVA Box Agent']['Configured'] = True
                else:
                    softwaredata['LAVA Box Agent']['Configured'] = False
    softwaredata['LAVA Controls Agent'] = {}
    try:
        import lavacontrolscorelib
    except:
        softwaredata['LAVA Controls Agent']['Installed'] = False
        pass
    else:
        softwaredata['LAVA Controls Agent']['Installed'] = True
        softwaredata['LAVA Controls Agent']['Version'] = lavacontrolscorelib.version()
        config2 = configparser.ConfigParser()
        try:
            config2.read([lavacontrolsagentconfigfile])
        except:
            pass
            msg = ('Error in {}!'.format(gotthefunc))
            print(gotthefunc, msg, 40)
            err = traceback.format_exc()
            msg = ('Error in {} Detail: {}'.format(gotthefunc,err))
            print(gotthefunc, msg, 10)
        else:
            try:
                lcatoken = config2.get('system', 'token')
            except:
                pass
                msg = ('Error in {}!'.format(gotthefunc))
                print(gotthefunc, msg, 40)
                err = traceback.format_exc()
                msg = ('Error in {} Detail: {}'.format(gotthefunc,err))
                print(gotthefunc, msg, 10)
                softwaredata['LAVA Controls Agent']['Configured'] = False
            else:
                if len(lcatoken) > 5:
                    softwaredata['LAVA Controls Agent']['Configured'] = True
                else:
                    softwaredata['LAVA Controls Agent']['Configured'] = False
    return(softwaredata)

if __name__ == "__main__":
    app.run(host='0.0.0.0')
