#!/usr/bin/python3

# ## {R2D2919B742E} ##
# ###########################################################################
# What if magic existed?
# What if a place existed where your every thought and dream come to life.
# There is only one catch: it has to be written down.
# Such a place exists, it is called programming.
#    - Scott Taylor Reph, RightThumb.com
# ###########################################################################
# ## {C3P0D40fAe8B} ##
##################################################
import os, sys, time
##################################################
import _rightThumb._construct as __
appDBA = __.clearFocus( __name__, __file__ )
__.appReg = appDBA
def focus( parentApp='', childApp='', reg=True ):
    global appDBA
    f = __.appName( appDBA, parentApp, childApp )
    if reg:
        __.appReg = f
    return f
__.registeredApps.append( focus() )
import _rightThumb._base3 as _
_.load()
##################################################
import _rightThumb._vars as _v
import _rightThumb._string as _str
##################################################

def appSwitches():
    _.switches.register( 'Remove', '-r,-remove', 'exec shell_exec', isRequired=True )
    _.switches.register( 'Files', '-f,-file,-files','/usr/local/php74/lib/php.ini', isData='name', description='Files', isRequired=True )
    # _.switches.register( 'WebReboot', '-reboot,-webreboot' )
    _.switches.register( 'Pause', '-pause', '120' )
    _.switches.register( 'Simulate', '-sim' )

_.autoBackupData = __.setting('receipt-log')
__.releaseAcquiredData = __.setting('receipt-file')
__.myFileLocations_SKIP_VALIDATION = False
__.isRequired_Pipe = False
__.isRequired_Pipe_or_File = False
__.pre_error = False
__.switch_raw = []
# __.switch_raw = [ 'Delim' ]
# __.isRequired_or_List = ['Pipe','Files','Plus']
# __.setting( 'app-switches-raw', [ 'Delim' ] )


_.appInfo[focus()] = {
    'file': 'vps-hoth-7facG-szYrXM-php.ini-fn.py',
    'liveAppName': __.thisApp( __file__ ),
    'description': 'removes functions from php.ini file',
    'categories': [
                        'hoth',
                        'server',
                        'vps',
                        'https',
                        'http',
                        'www',
                        'php',
                        'php.ini',
                        'ini',
                        '.ini',
                ],
    'usage': [
                        # 'epy another',
                        # 'e nmap',
                        # '',
    ],
    'relatedapps': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'prerequisite': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'examples': [
                        _.hp('p vps-hoth-7facG-szYrXM-php.ini-fn -f /usr/local/php81/lib/php.ini -remove exec shell_exec'),
                        _.hp('p vps-hoth-7facG-szYrXM-php.ini-fn -f /usr/local/php74/lib/php.ini -remove exec shell_exec'),
                        '',
    ],
    'columns': [
                       # { 'name': 'name', 'abbreviation': 'n' },
                       # { 'name': '{1}', 'abbreviation': '{0}', 'sort': '{2}' },
    ],
    'aliases': [
                       # 'this',
                       # 'app',
    ],
    'notes': [
                       # {},
    ],
}

_.appData[focus()] = {
        'start': __.startTime,
        'uuid': '',
        'audit': [],
        'pipe': False,
        'data': {
                    'field': {'sent': [], 'received': [] }, # { 'label': '', 'context': [],  }
                    'table': {'sent': [], 'received': [] }, 
        },
    }



def registerSwitches( argvProcessForce=False ):
    global appDBA
    if not __.appReg == appDBA and appDBA in __.appReg:

        if not __name__ == '__main__':
            _.argvProcess = argvProcessForce
        else:
            _.argvProcess = True

        _.load()
        _.appInfo[__.appReg] = _.appInfo[appDBA]
        _.appData[__.appReg] = _.appData[appDBA]
    __.constructRegistration( _.appInfo[__.appReg]['file'],__.appReg )
    appSwitches()

    _.myFileLocation_Print = False
    _.switches.trigger( 'Files', _.myFileLocations, vs=True )
    _.switches.trigger( 'Folder', _.myFolderLocations )
    _.switches.trigger( 'URL', _.urlTrigger )
    _.switches.trigger( 'Ago', _.timeAgo )
    _.switches.trigger( 'Duration', _.timeFuture )
    
    _.defaultScriptTriggers()
    _.switches.process()


if not __name__ == '__main__':
    _.argvProcess = False
else:
    _.argvProcess = True

registerSwitches()


def fieldSet( switchName, switchField, switchValue, theFocus=False ):
    if not type( theFocus ) == bool:
        theFocus = theFocus
    _.switches.fieldSet( switchName, switchField, switchValue, theFocus )


if __name__ == '__main__':
    if not sys.stdin.isatty():
        _.setPipeData( sys.stdin.readlines(), __.appReg, clean=True )


_.postLoad( __file__ )

########################################################################################
# START

import requests

def fn_list(row):
    row = row.replace(' ','')
    row = row.replace(' ','')
    items = []
    for x in row.split('=')[1].split(','):
        items.append(x)
    return items

def fn_list2(row):
    row = row.replace(' ','')
    row = row.replace(' ','')
    items = []
    for x in row.split('=')[1].split(','):
        if not x in _.switches.values('Remove'):
            items.append(x)
    return items

def run():
    # try:
    #     test = requests.get('https://eyeformeta.com/online-py/').content.decode("utf-8")
    # except Exception as e:
    #     _.pr('url error')
    #     return None

    foundAll = False
    # if 'r2d2' in test.lower() or 'c3po' in test.lower():
    if True:
        for i,path in enumerate( _.switches.values('Files') ):
            file = []
            path = __.path(path)
            _.pr('START:',path)
            php_ini = _.getText(path,raw=True)
            found = False
            for i,row in enumerate( php_ini.split('\n') ):
                if row.startswith('disable_functions'):
                    row=row.replace('\r','')
                    row=row.replace('\t','')
                    row=row.replace(' ','')
                    items = fn_list(row.lower())
                    for x in _.switches.values('Remove'):
                        if x.lower() in items:
                            found=True
                            foundAll=True

            if not found:
                _.cp( 'Not found! - clear', 'green' )

            if found:
                fileBackup.switch( 'Input', path )
                fb = fileBackup.action()
                _.pr('Backup:',fb)
                for i,row in enumerate( php_ini.split('\n') ):
                    # _.pr(row)
                    if row.startswith('disable_functions'):
                        _.pr()
                        _.pr(row)
                        _.pr()
                        items = fn_list2(row)
                        row='disable_functions = '+','.join(items)
                        _.pr(row)
                        _.pr()

                    file.append(row)
                _.pr('END:',path)
                _.saveText(file,path)
                fb = fileBackup.action()
    if foundAll:
        _send.imp.action( to='8136901260', from_='8136901260',body='php.ini fn fixed, reboot server\nhttps://eyeformeta.com/actions/reboot/' )
        p=5
        if _.switches.isActive('Pause'):
            p = int(_.switches.value('Pause'))
        _.pr(p)
        time.sleep(p)
        _.pr('NOTE: restart')
        n = int(str(time.time()).split('.')[0])
        # if _.switches.isActive('WebReboot'):
        if True:
            f = '/home/admin/domains/eyeformeta.com/private_html/actions/reboot/stamps.txt'
            gotSignal = False
            sig=0
            _.pr('waiting for admin to OK via: https://eyeformeta.com/actions/reboot/')
            if os.path.isfile(f):
                os.unlink(f)
            while True:
                done=False
                if os.path.isfile(f):
                    gotSignal=True
                    break
                time.sleep(5)

            pass
            if os.path.isfile(f):

                # _.pr( sig, '>', n )
                _.pr('got signal, rebooting')
                if _.switches.isActive('Simulate'):
                    _.pr('sym reboot')
                else:
                    os.system('reboot')

        # try:
        #     os.system('reboot')
        # except Exception as e:
        #     _.pr('error')


def action():
    _.pr('_________________________________________________________________________________')
    _.pr(_.isDate(time.time())['iso'])
    if not _.switches.isActive('Remove'):
        _.e( '-remove is isRequired' )
    run()


fileBackup = _.regImp( focus(), 'fileBackup' )
fileBackup.switch( 'Silent' )
fileBackup.switch( 'Flag', 'imdb' )
fileBackup.switch( 'isRunOnce' )
fileBackup.switch( 'DoNotSchedule' )
_send =  _.regImp( __.appReg, 'vps-srv-7facG-twilio-send' )


########################################################################################
if __name__ == '__main__':
    action()
    __.isExit()





