#!/usr/bin/python3
# Display Engine Client - Copyright 2022 LAVA Controls - Stephen Loeckle

import configparser
import argparse
import traceback
from pathlib import Path

def main():

# Set some defaults
    licensekey = ''
    boxtype = 'display'
    interval = '1'
    user = 'kiosk'
    loglevel = '10'
    smtphost = 'localhost'
    email = 'sloeckle@lucidnetworks.net'
    browsername = 'chrome'
    browserpath = '/usr/bin/google-chrome'
    browseroptions = '--allow-file-access-from-files --disable-session-crashed-bubble --disable-infobars --kiosk https://www.lavacontrols.com'
    httpproxy = ''
    dailyreboottime = None
    startupsecs = None
    systemanalysissecs = None
    systemanalysisproblemsecs = None
    singlecolordetection = None
    
# Try to read old nexp-controls.conf for license key
    nexpcontrolsconffile = Path('/etc/nexp-controls/nexp-controls.conf')
    if nexpcontrolsconffile.is_file():
        nexpcontrolsconfig = configparser.ConfigParser()
        try:
            nexpcontrolsconfig.read(['/etc/nexp-controls/nexp-controls.conf'])
            try:
                licensekey = nexpcontrolsconfig.get('system', 'roomkey')
            except:
                msg = ("Can't read /etc/nexp-controls.conf for migration!")
                print(msg)
                err = traceback.format_exc()
                print(err)
                pass
        except:
            pass
        
# Load in existing declient.conf so current valid options aren't lost
    
    config = configparser.ConfigParser()
    try:
        config.read(['/etc/declient/declient.conf'])
        try:
            licensekey = config.get('system', 'licensekey')
        except:
            pass
        try:
            boxtype = config.get('system', 'boxtype')
        except:
            pass
        try:
            singlecolordetection = config.get('system', 'singlecolordetection')
        except:
            pass
        try:
            dailyreboottime = config.get('system', 'dailyreboottime')
        except:
            pass
        try:
            interval = config.get('system', 'interval')
        except:
            pass
        try:
            startupsecs = config.get('system', 'startupsecs')
        except:
            pass
        try:
            systemanalysissecs = config.get('system', 'systemanalysissecs')
        except:
            pass
        try:
            systemanalysisproblemsecs = config.get('system', 'systemanalysisproblemsecs')
        except:
            pass
        try:
            user = config.get('system', 'user')
        except:
            pass
        try:
            loglevel = config.get('system', 'loglevel')
        except:
            pass
        try:
            smtphost = config.get('system','smtphost')
        except:
            pass
        try:
            email = config.get('system','emailnotification')
        except:
            pass
        try:
            browsername = config.get('browser','name')
        except:
            pass
        try:
            browserpath = config.get('browser','path')
        except:
            pass
        try:
            browseroptions = config.get('browser','options')
        except:
            pass
        try:
            httpproxy = config.get('network','httpproxy')
        except:
            pass

    except:
        msg = ("Can't read /etc/declient/declient.conf")
        print(msg)
        err = traceback.format_exc()
        print(err)        
        pass
        
# CLI arguments for specifying new options
    
    parser = argparse.ArgumentParser(description='Display Engine Client build-config')
    configgroup = parser.add_argument_group('config')
    configgroup.add_argument('-i', '--interval', help = 'Set cloud check interval.', nargs=1)
    configgroup.add_argument('-l', '--license', help = 'Set license key.', nargs=1)
    configgroup.add_argument('-b', '--boxtype', help = 'Set box type.', choices=['display','control'], nargs=1)
    configgroup.add_argument('-u', '--user', help = 'Set run-as user.', nargs=1)
    configgroup.add_argument('-log', '--loglevel', help = 'Set loglevel.', choices=[10,20,30,40,50], nargs=1)
    configgroup.add_argument('-smtp', '--smtphost', help = 'Set smtp host.', nargs=1)
    configgroup.add_argument('-e', '--emailnotification', help = 'Set email notification parameter.', nargs=1)
    configgroup.add_argument('-bn', '--browsername', help = 'Set browser name, e.g. chrome.', nargs=1)
    configgroup.add_argument('-bp', '--browserpath', help = 'Set browser path, e.g. /usr/bin/google-chrome', nargs=1)
    configgroup.add_argument('-bo', '--browseroptions', help = 'Set browser options (must be in quotes), e.g. --disable-session-crashed-bubble --disable-infobars --kiosk http://lucidnetworks.net', nargs=1)
    configgroup.add_argument('-hp', '--httpproxy', help = 'Set network http proxy, e.g. http://proxy.lavacontrols.com:8080 (This will cover http and https proxy environment variable)', nargs=1)
    args = parser.parse_args()
    if args.interval:
        interval = args.interval[0]
    if args.license:
        licensekey = args.license[0]
    if args.boxtype:
        boxtype = args.boxtype[0]
    if args.user:
        user = args.user[0]
    if args.loglevel:
        loglevel = args.loglevel[0]
    if args.smtphost:
        smtphost = args.smtphost[0]
    if args.emailnotification:
        email = args.emailnotification[0]
    if args.browsername:
        browsername = args.browsername[0]
    if args.browserpath:
        browserpath = args.browserpath[0]
    if args.browseroptions:
        browseroptions = args.browseroptions[0]
    if args.httpproxy:
        httpproxy = args.httpproxy[0]
    if (not args.user and not args.license and not args.boxtype and not args.interval and not args.loglevel and not args.smtphost and not args.emailnotification and not args.browsername and not args.browserpath and not args.browseroptions and not args.httpproxy):
        msg = ('No command line arguments sent. Loading defaults then previous configuration.')
        print(msg)

    newconfig = configparser.ConfigParser()
    newconfig.add_section('system')
    newconfig.set('system','licensekey',licensekey)
    newconfig.set('system','boxtype',boxtype)
    newconfig.set('system','interval',interval)
    if singlecolordetection:
        newconfig.set('system','singlecolordetection',singlecolordetection)
    if dailyreboottime:
        newconfig.set('system','dailyreboottime',dailyreboottime)
    if startupsecs:
        newconfig.set('system','startupsecs',startupsecs)
    if systemanalysissecs:
        newconfig.set('system','systemanalysissecs',systemanalysissecs)
    if systemanalysisproblemsecs:
        newconfig.set('system','systemanalysisproblemsecs',systemanalysisproblemsecs)
    newconfig.set('system','user',user)
    newconfig.set('system','loglevel',loglevel)
    newconfig.set('system','smtphost',smtphost)
    newconfig.set('system','emailnotification',email)
    newconfig.add_section('browser')
    newconfig.set('browser','name',browsername)
    newconfig.set('browser','path',browserpath)
    newconfig.set('browser','options',browseroptions)
    newconfig.add_section('network')
    newconfig.set('network','httpproxy',httpproxy)

    with open('/etc/declient/declient.conf','w') as config_file:
        newconfig.write(config_file)

if __name__ == '__main__':
   main()
