#!/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( 'User', '-user' )
    _.switches.register( 'Password', '-password' )
    _.switches.register( 'MD5', '-md5,-MD5' )
    _.switches.register( 'Just-Return', '--c' )
    
    _.switches.register( 'Add', '-add' )

    _.switches.register( 'Token', '-token' )
    _.switches.register( 'App', '-app' )

    _.switches.register( 'Dump', '-dump' )
    _.switches.register( 'Test', '-t,-test' )
__.setting('receipt-log',False)
_.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()] = {
    'app': '7facG-FoDn0t',
    'file': 'vps-auth.py',
    'liveAppName': __.thisApp( __file__ ),
    'description': 'authenticate on server',
        # _.ail(1,'subject')+
        # _.aib('one')+
    'categories': [
                        'auth',
                        'authorize',
                ],
    'usage': [
                        # 'epy another',
                        # 'e nmap',
                        # '',
    ],
    'relatedapps': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'prerequisite': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'examples': [
                        _.hp('p vps-auth -user scott -password taco -md5 -add'),
                        '',
    ],
    '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 find_token(token):
    global security
    for u in security:
        if gen_token(u) == token:
            return True
    return False

def gen_token(user):
    return _hash.string( user+'-r2d2-c3p0' )

def action():
    global security
    load()
    if _.switches.isActive('Test'):
    if len(_.switches.all())==0:
        for k in security: _.pr(k)
        return None
    if _.switches.isActive('User') and len(_.switches.all())==1:
        access = _.getTable( 'vps-auth-access.index' )
        u = _.switches.value('User')
        t=gen_token(u)
        _.pr('token:', t )
        if u in security: _.pr('pass:',security[u])
        if t in access: _.pr('access:',c='green'); _.pr( '\n'.join( access[t] ) );
        return None

    if _.switches.isActive('Password'):
        _.switches.fieldSet( 'MD5', 'active', True )
        _.switches.fieldSet( 'Add', 'active', True )


    t = _.switches.value('Token')
    a = _.switches.value('App')

    if _.switches.isActive('Dump'):
        table=[]
        for u in security:
            table.append({ 'user': u, 'token': gen_token(u) })
        _.tables.register( 'data', table )
        _.tables.print( 'data', 'user,token' )
        return table
    if _.switches.isActive('Token') and _.switches.isActive('App') and _.switches.isActive('Add'):
        access = _.getTable( 'vps-auth-access.index' )
        if not t in access:
            access[t] = []
        if not a in access[t]:
            access[t].append(a)
        _.saveTable(access,'vps-auth-access.index',p=0)
        return access
    elif _.switches.isActive('Token') and _.switches.isActive('App'):
        access = _.getTable( 'vps-auth-access.index' )
        if t in access and a in access[t]:
            if not _.switches.isActive('Just-Return'):
                _.pr('pass')
            return 'pass'
        exists = False
        for tt in access:
            if a in access[tt]:
                exists=True
        if not exists:
            if not _.switches.isActive('Just-Return'):
                _.pr('app')
                return 'app'
        if not _.switches.isActive('Just-Return'):
            _.pr('fail')
            return 'fail'
        else:

            if not _.switches.isActive('Just-Return'):
                _.pr('fail')
            return 'fail'
    elif _.switches.isActive('Token'):
        t = _.switches.values('Token')[0]
        if find_token(t):
            if not _.switches.isActive('Just-Return'):
                _.pr('pass')
            return 'pass'
        else:
            if not _.switches.isActive('Just-Return'):
                _.pr('fail')
            return 'fail'



    u = _.switches.values('User')[0]
    u = u.lower()
    u = _str.do( 'dup', u, ' ' )
    u = _str.do( 'be', u, ' ' )
    u = _str.do( 'an', u, '-_.' )

    p = _.switches.values('Password')[0]
    # _.pr(p)
    if _.switches.isActive('MD5'):
        p = _hash.string(p)
    p = p.replace('\n','')
    p = p.replace('\r','')
    p = p.replace(' ','')
    # _.pr(p)
    if _.switches.isActive('Add'):
        # security[u] = _hash.string( p )
        security[u] = p
        _.saveTable(security,'vps-auth.index',p=0)

    # _.pr('user', u)
    # _.pr('pass', p)
    # _.pr('test', u in security)

    if u in security:
        # _.pr('found: user', '|'+p+'|', security[u] )
        if p == security[u] or _hash.string( p ) == security[u]:
            t = gen_token(u)
            if not _.switches.isActive('Just-Return'):
                _.pr(t)
            return t
    if not _.switches.isActive('Just-Return'):
        _.pr('fail')
    return 'fail'

def load():
    global security
    security = _.getTable( 'vps-auth.index' )

import _rightThumb._md5 as _hash
# _hash.string( file )
# _hash.file( file )


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





