#!/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( 'When', '-when', 'now 1w 1m 1d' )
    _.switches.register( 'Folder', '-f,-folder' )

    _.switches.register( 'Task', '-task' )
    _.switches.register( 'Local', '-l,-local' )
    _.switches.register( 'Remote', '-r,-remote' )
    _.switches.register( 'Project', '-p,-project' )



_.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-app-5AF8BE82-backup.py',
    'liveAppName': __.thisApp( __file__ ),
     'description': 'vps backup tool',
    'categories': [
                        'vps',
                        'backup',
                        'tool',
                ],
    'usage': [
                        # 'epy another',
                        # 'e nmap',
                        # '',
    ],
    'relatedapps': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'prerequisite': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'examples': [
                        _.hp('p thisApp -file file.txt'),
                        '',
    ],
    '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 file(path):
    global record
    global base
    global index
    base = base.replace(os.sep+os.sep,os.sep)
    base = base.replace(os.sep+os.sep,os.sep)
    if not base.endswith(os.sep):
        base+=os.sep

    # index[path.replace(base,'')] = _dir.info(path)
    index[path.replace(base,'').replace('\\','/')] = os.path.getmtime(path)

def getFolder(folder,r=True):
    if not os.path.isdir(folder):
        return None
    for file in os.listdir(folder):
        path = folder +os.sep+ file
        if os.path.isfile(path):
            process(path)
        elif r:
            getFolder(path,r)

def task_local_index(folder):
    global index
    global base
    base=folder
    getFolder(folder)

def task_remote_index(project):
    global index
    global base
    global backup_user
    base='/home/'+backup_user+'/backup/'+project
    _v.mkdir(base)
    getFolder(base)

def task_local_ssh_copy_json_to_remote():
    file=_v.myTables+os.sep+'vps-app-5AF8BE82-backup.json'
    pass

def task_local_ssh_index_run():
    pass

def task_local_ssh_index_get():
    global record
    global backup_user
    local=_v.stmp+os.sep+'vps-app-5AF8BE82-backup-(remote-index)'+record['project']+'.json'
    remote='/home/'+backup_user+'/backup/settings.json'

    cmd='scp USER@bespin.eyeformeta.com:"REMOTE"  "LOCAL"'
    cmd = cmd.replace('USER',backup_user).replace('REMOTE',remote).replace('LOCAL',local)
    subprocess.getoutput(cmd)
    remote_index = _.getTable2(local)
    task_local_xref_indexes(remote_index)

def task_local_xref_indexes(remote):
    global index
    files = []
    for f in index:
        if not f in remote:
            files.append(f)
        elif index[f] > remote[f]:
            files.append(f)
    task_local_create_temp(files)

def task_local_create_temp(files):
    global record
    folder=_v.stmp+os.sep+'vps-app-5AF8BE82-backup-'record['project']
    base=record['folder']
    bk=folder+'.zip'
    for f in files:
        p=base+os.sep+f
        p=p.replace('/',os.sep)
        p = p.replace(os.sep+os.sep,os.sep)
        p = p.replace(os.sep+os.sep,os.sep)
        t=folder+os.sep+f
        t=t.replace('/',os.sep)
        t = t.replace(os.sep+os.sep,os.sep)
        t = t.replace(os.sep+os.sep,os.sep)
        try:
            os.link(p,t)
        except Exception as e:
            _.pr(e)
    cmd = 'zip -r "OUTPUT" "INPUT"'.replace('OUTPUT',bk).replace('INPUT',folder)
    subprocess.getoutput(cmd)
    task_local_ssh_upload_bk(bk)    

def task_local_ssh_upload_bk(bk):

def action():
    schedule = False
    if not _.switches.isActive('Task') and not _.switches.isActive('Local') and not _.switches.isActive('Remote'):
        schedule = True

    folders = [os.getcwd()]
    if _.switches.isActive('Folder') and len(_.switches.value('Folder')):
        folders = _.switches.values('Folder')
    pass





    # folder as id to replace any settins changes
    {

        'folder': {
            'project': uuid,
            'frequently': '',
            'cron': '',
            'folder': '',
        }
    }


# import _rightThumb._dir as _dir
backup_user='scott'

# LATER filename = /etc/hostname
# LATER only added appended on host copied as needed
import subprocess

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





