#!/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( 'Text', '-t,-text,-i' )
    _.switches.register( 'Password', '-password' )
    _.switches.register( 'Key', '-key' )
    _.switches.register( 'ForceKey', '-f,-force,-fkey,-fk' )
    _.switches.register( 'Save', '-save' )
    _.switches.register( 'Secure', '-secure' )

# _.autoBackupData = __.setting('receipt-log')
# __.releaseAcquiredData = __.setting('receipt-file')
_.autoBackupData = False
__.releaseAcquiredData = False
__.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-text-key.py',
    'liveAppName': __.thisApp( __file__ ),
    'description': 'text key',
        # _.ail(1,'subject')+
        # _.aib('one')+
    'categories': [
                        'key',
                        'text',
                ],
    'usage': [
                        # 'epy another',
                        # 'e nmap',
                        # '',
    ],
    'relatedapps': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'prerequisite': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'examples': [
                        _.hp('p vps-text-key -t Alexandria'),
                        _.hp('p vps-text-key -t 20220811150810'),
                        _.hp('p vps-text-key -t 20220811150810 -password test -force'),
                        _.hp('p vps-text-key -t 20220811150810 -password test -force -key'),
                        '',
    ],
    '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 shapeKee(tn='8136901260', pin=None, key=None, rkey=None, skip=None, h=None):
    tn=str(tn)
    tn=tn.replace('key: {','key:{')
    tn=_str.do('dup',tn,' ')
    tn=_str.do('be',tn,' ')
    tn=tn.replace(' ','-')

    try:
        from random import randrange
    except Exception as e:
        pass
    
    o=0
    vicA=[]
    vicB=[]
    # vicA.append(tn)
    while o < len(tn):
        o+=1
        try:
            n=tn[o:]
            if len(n):
                vicA.append(n)
        except Exception as e:
            break
        try:
            n=tn[:o]
            if len(n):
                vicB.append(n)
        except Exception as e:
            break
    result=list(set(vicA+vicB))
    result.sort()
    e=None
    b=None
    ones=[]

    def be(i,table,text):
        ii=i
        last=1
        group = []
        group.append(i)
        # _.pr(568)
        while True:
            # if ii > 5000:
            #     # _.pr(len(table))
            #     break
            ii+=1
            try:
                ik = len( table[ii] )
                if not ik == (last+1):
                    break
                else:
                    last=ik
                    group.append(ii)
            except Exception as e:
                break
                pass
        # _.pr(568)
        if group and len(group) == len(text):
            group.reverse()
            return group[0]


        ii=i
        last=1
        group = []
        group.append(i)
        while True:
            ii-=1
            try:
                ik = len( table[ii] )
                if not ik == (last+1):
                    break
                else:
                    last=ik
                    group.append(ii)
            except Exception as e:
                pass
        ii=i
        if group and len(group) == len(text):
            # group.reverse()
            return group[0]



        return None


    for i,rK in enumerate(result):
        ki=len(rK)
        if ki == 1:
            test=be(i,result,tn)
            if not test is None:
                b=i
                e=test
    
    
    # _.pr(b)
    # _.pr(e)

    # if not b is None and e > b:
    #     result.reverse()
    try:
        import _rightThumb._md5 as _md5
    except Exception as e:
        _.e(e)
    
    if not key is None:
        txt = '\n'.join(result)
        if not skip is None:
            pin=''
        elif skip is None:
            if pin is None:
                if _.switches.isActive('Password'):
                    pin=' '.join(_.switches.values('Password'))
                else:
                    import getpass
                    # pin=input('pin?: ')
                    pin=getpass.getpass()
        pin+='1980'
        md5=_md5.string('r2d2'+tn+pin+txt+pin+tn+'c3p0')
        key=_.ddelim( md5, 'uuid' )
        if _.switches.isActive('Key') or rkey:
            return key
        KEY    = '''_________________________________________________________________________________
#crypt #key #shapeKee 3e1647481496
secret: {tn}

{txt}

key: {key}
_________________________________________________________________________________'''.replace('{tn}',tn).replace('{txt}',txt).replace('{key}',key)
        if skip is None:
            KEY = KEY.replace(' 3e1647481496', ' #pin')
        else:
            KEY = KEY.replace(' 3e1647481496', '')
        
        return KEY
        pass


    if h is None:
        return result
    
    if not type(h) == str:
        h='md5'
    return _md5.string( '\n'.join(result) ,h)



def secure(key):
    a=None
    b=None
    for line in key.split('\n'):
        if line.startswith('key: {'):
            parts=line.split('{')[1].split('}')[0].split('-')
            a=parts[0]
            b=parts[4]
            key=key.replace( '-'+b, '' )
            # _.pr(parts)
            # sys.exit()
    return { 'b': a, 'e': b, 'key': key }


_.v8=_.dot()
def action(pw=None,pin=None, key=None, rkey=None):
    _.v8.pin=pin
    # x = shapeKee(key=1)
    # _.pr(x)
    # return None


    if _.switches.isActive('ForceKey'):
        skip=None
    else:
        skip=True

    if not pw is None:
        key = shapeKee(tn=pw,key=key,pin=pin,rkey=rkey,skip=skip)
    elif _.switches.isActive('Text'):
        if len(_.switches.value('Text')):
            key = shapeKee( ' '.join(_.switches.values('Text')), key=1, skip=skip )
        else:
            key = shapeKee(  input('text: ') , key=1, skip=skip )
    else:
        key = shapeKee(key=1,skip=skip)

    if _.switches.isActive('Save'):
        s=_.switches.values('Save')[0]
        if _.switches.isActive('Secure'):
            dic = secure(key)
            key = dic['key']
            # _.pv(dic)
        _.saveText( key, s )
        if _.switches.isActive('Secure'):
            _steg = _.regImp( __.appReg, 'steg' )
            _steg.imp.action( path=s, hidden=dic['e'], password=dic['b'] )

    
    _.pr(key)

    return key
    # _.pr(key)
    # _.pr()
    # _.pr()
    # _.pr()
    # hashes = [
    #           'md5',
    #           'sha1',
    #           'sha224',
    #           'sha256',
    #           'sha384',
    #           'sha512',
    #           'sha3_224',
    #           'sha3_256',
    #           'sha3_384',
    #           'sha3_512',
    # ]
    # md5=_md5.string(key)
    # _.pr('key:', md5)
    # return md5
    # for hes in hashes:
    #   hash0=_md5.string(key,hes)
    #   _.pr('',hes, hash0)
    #   sys.exit()


import _rightThumb._md5 as _md5


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





