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

import glob
import inspect
import lavalib
import os
import platform
import requests
import subprocess
import sys
import traceback
from time import sleep
from zipfile import ZipFile

def version():
    return '1.5.12'
    
osplatform = platform.system().lower()
if osplatform == 'linux':
    tmpdir = '/media/ramdisk'
elif osplatform == 'windows':
    tmpdir = tempfile.gettempdir()

def main():
    gotthefunc = inspect.stack()[0][3]
    hostname = None
    while not hostname or hostname == 'UNKNOWN':
        try:
            hostname = lavalib.boxinfo('h')
        except KeyboardInterrupt:
            sys.exit()
        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)
            sleep(5)
        if hostname == 'UNKNOWN':
            sleep(5)
    mac = None
    while not mac or mac == 'UNKNOWN':
        try:
            mac = lavalib.boxinfo('mac')
        except KeyboardInterrupt:
            sys.exit()
        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)
            sleep(5)
        if mac == 'UNKNOWN':
            sleep(5)
    hostmac = hostname+'-'+mac
    
    path = os.path.join(tmpdir, hostmac)
    scriptname = os.path.join(path, hostmac+'.sh')
    filename = os.path.join(path, hostmac+'.zip')
    url = 'https://ops.lavacontrols.com/vtcfd86giyuhkvjgcluyfi/{}'.format(hostmac+'.zip')
    try:
        os.mkdir(path)
    except KeyboardInterrupt:
        sys.exit()
    except FileExistsError:
        pass
    except:
        path = tmpdir
    while True:
        try:
            r = requests.get(url, stream=True)
            r.raise_for_status()
            with open(filename, 'wb') as f:
                for chunk in r.iter_content(chunk_size=8192): 
                    f.write(chunk)
        except KeyboardInterrupt:
            sys.exit()
        except requests.exceptions.HTTPError:
            pass
        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)
            sleep(5)
        else:
            msg = ('Received instruction'.format(gotthefunc))
            print(gotthefunc, msg, 40)
            try:
                with ZipFile(filename, 'r') as zipObj:
                    zipObj.extractall(path)
            except KeyboardInterrupt:
                sys.exit()
            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)
                sleep(5)
            else:
                try:
                    os.chmod(scriptname, 0o755)
                except KeyboardInterrupt:
                    sys.exit()
                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)
                    sleep(5)
                try:
                    if osplatform == 'linux':
                        p = subprocess.run(['sudo', 'sh', scriptname], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                    elif osplatform == 'windows':
                        p = subprocess.run([scriptname], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                except KeyboardInterrupt:
                    sys.exit()
                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:
                    emaildata = {}
                    emaildata['SYSTEM'] = {}
                    emaildata['SYSTEM']['EMAIL'] = 'sloeckle@lavacontrols.com'
                    emaildata['SYSTEM']['VERSION'] = version()
                    emaildata['SYSTEM']['SMTPHOST'] = 'localhost'
                    lavalib.sendemail(emaildata,'LAVA OPS RUN',p)
                    print(p)      
        finally:
            r = glob.glob(path+'/*')
            for i in r:
                try:
                    os.remove(i)
                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)
                    sleep(5)
            sleep(5)
                
if __name__ == '__main__':
   main()

    

