#!/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():
    pass
    # _.switches.register( 'UUID', '-uuid' )
    # _.switches.register( 'Delete', '-delete' )
    # _.switches.register( 'Update', '-update' )


_.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-7GoeaZ-scheduler.py',
    'liveAppName': __.thisApp( __file__ ),
     'description': 'schedule email app-7facG-7GoeaZ (B518DA1C)',
    'categories': [
                        'schedule',
                        'email',
                ],
    'usage': [
                        # 'epy another',
                        # 'e nmap',
                        # '',
    ],
    'relatedapps': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'prerequisite': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'examples': [
                        _.hp('p vps-hoth-7facG-7GoeaZ-scheduler'),
                        '',
    ],
    '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

# def schedule_email(d,t,uuid):
#     global ats
#     _.pr( uuid )
#     cmd = """ echo " /home/admin/domains/eyeformeta.com/public_html/apps/clients/7i0ZA/schedule/run.sh """+uuid+"""  >>/home/admin/domains/eyeformeta.com/public_html/apps/clients/7i0ZA/schedule/schedule.log" | at """+t+""" """ + d
#     _.pr( cmd )
#     output = subprocess.getoutput(cmd)
#     for line in output.split('\n'):
#         if line.startswith('job '):
#             at = line.split(' ')[1]
#             ats.append(at)
#             _.pr( 'job: 'at )



# def gen_schedule( nday, sday ):
#     if nday is None:
#         sub = sday
#     else:
#         sub = nday
#     try:
#         sub = _.isDate(sub)['date']
#     except Exception as e:
#         _.pr( 'Error: bad dates', nday, sday )
#         raise e
#         sys.exit()
    



def action():
    # uuid = _.switches.values('UUID')[0]
    USER_NAME = "admin_user-meta-web"
    PASSWORD = _keychain.imp.key('sql')
    # _.pr(PASSWORD)
    import pymysql.cursors
    SERVER_URL = "localhost"
    DB = "admin_db-meta-web"
    SQL_CONNECTION = pymysql.connect(host=SERVER_URL,
    user=USER_NAME,
    passwd=PASSWORD,
    db=DB,
    charset='utf8mb4',
    cursorclass=pymysql.cursors.DictCursor,
    autocommit=True)
    cursor = SQL_CONNECTION.cursor()
    sql = 'SELECT id, app, uuid, cron, do, sday, stime, del FROM app_C3P0R2D2_scheduler ORDER BY id DESC;'
    sql_exec = cursor.execute(sql)
    records = cursor.fetchall()
    _.pv(records)
    if not records:
        # _.pr('no records')
        SQL_CONNECTION.close()
        return None

    _.pr( '__________________________________________________________________________________' )
    _.pr( '### eye for meta - scheduler -', _.isDate(time.time())['fdate'] )


    dump = simplejson.dumps(records, indent=4, sort_keys=False)
    records = simplejson.loads(dump)

    fileBackup.switch( 'Input', '/var/spool/cron/root' )
    fileBackup.switch( 'Flag', 'app-B518DA1C' )
    recoveryFile = fileBackup.do( 'action' )
    _.pr('backup:', recoveryFile)


    for rec in records:


        cmd=''
        uuid = rec['uuid']
        _.pr(uuid)
        error=0
        if rec['del'] == 1:
            _.cp('Delete')
        cursor.execute('DELETE FROM app_C3P0R2D2_scheduler WHERE id='+str(rec['id'])+';')

        if rec['del'] == 0:
            if not rec['stime'] is None and len(rec['stime']) and not rec['sday'] is None and len(rec['sday']):
                try:
                    sub = _.isDate(rec['sday'])['date']
                except Exception as e:
                    _.pr( 'Error: bad dates', nday, sday )
                    raise e
                    sys.exit()

                cmd = rec['stime'].split(':')[1] +' '+ rec['stime'].split(':')[0] +' '+ sub.split('-')[2] +' * * ' + rec['do']
            elif not rec['cron'] is None and len(rec['cron']):
                cmd = rec['cron'] +' '+ rec['do']
            else:
                _.pr('Error')
                error=1
        error=0
        if not error:
            _.pr(cmd)
            cron = _.getText('/var/spool/cron/root',raw=True,clean=2).split('\n')
            cr = []

            for line in cron:
                if not uuid in line:
                    cr.append(line.replace('\n',''))


            if rec['del'] == 0:
                cr.append( cmd )

            code = '\n'.join(cr)
            code = _str.cleanBE(code,' ')
            code = _str.cleanBE(code,'\n')
            code = _str.replaceDuplicate(code,'\n')
            code = _str.cleanBE(code,'\n')
            code = _str.cleanBE(code,' ')

            _.saveText( code, '/var/spool/cron/root' )

            output = subprocess.getoutput( 'echo "" | EDITOR="tee -a" crontab -e' )
            _.pr(output)

    SQL_CONNECTION.close()



_keychain = _.regImp( __.appReg, 'keychain' )
import simplejson


fileBackup = _.regImp( __.appReg, 'fileBackup' )

# fileBackup.switch( 'Silent' )
fileBackup.switch( 'isRunOnce' )
fileBackup.switch( 'DoNotSchedule' )
import subprocess

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





