#!/usr/bin/env python

import getopt, sys, os
import gettext
 
# First of all, we need to change the working directory to the directory of w3af.
currentDir = os.getcwd()
scriptDir = os.path.dirname(sys.argv[0]) or '.'
os.chdir( scriptDir )

def backToCurrentDir():
    os.chdir( currentDir )

# Translation stuff
gettext.install('w3af', 'locales/')

# Now we can load all modules and stuff...
from core.controllers.w3afException import w3afException
import core.controllers.outputManager as om

try:
    om.out.setOutputPlugins( ['console'] )
except w3afException, w3:
    print 'Something went wrong, w3af failed to init the output manager. Exception: ', str(w3)
    sys.exit(-9)
    

def usage():
    om.out.information('w3af - Web Application Attack and Audit Framework')
    om.out.information('')
    om.out.information('Options:')
    om.out.information('    -h              Print this help message.')
    om.out.information('    -s <file>       Execute a script file.')
    om.out.information('    -p <profile>    Run with the selected profile')
    om.out.information('')
    om.out.information('http://w3af.sourceforge.net/')

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "p:i:hs:get", [] )
    except getopt.GetoptError:
        # print help information and exit:
        usage()
        return -3
    scriptFile = None
    profile = None
    for o, a in opts:
        if o in ( "-e"  ):
            # easter egg
            import base64
            om.out.information( base64.b64decode( 'R3JhY2lhcyBFdWdlIHBvciBiYW5jYXJtZSB0YW50YXMgaG9yYXMgZGUgZGVzYXJyb2xsbywgdGUgYW1vIGdvcmRhIQ==' ) )
        if o in ( "-t"  ):
            # Test all scripts that have an assert call
            from core.controllers.misc.w3afTest import w3afTest
            w3afTest()
            return 0
        if o == "-s":
            scriptFile = a
        if o in ('-p', '--profile'):
            # selected profile
            profile = a
        if o == "-h":
            usage()
            return 0
    
    # console
    from core.ui.consoleUi.consoleUi import consoleUi
    
    commandsToRun = []
    if scriptFile != None:
        try:
            fd = open( scriptFile )
        except:
            om.out.error('Failed to open file : ' + scriptFile )
            sys.exit(2)
        else:
            commandsToRun = []
            for line in fd:   
                line = line.strip()
                if line != '' and line[0] != '#':   # if not a comment..
                    commandsToRun.append( line )
            fd.close() 
    elif profile is not None:
        commandsToRun = ["profiles use %s" % profile]

    console = consoleUi(commands=commandsToRun)
    console.sh()


if __name__ == "__main__":
    errCode = main()
    backToCurrentDir()
    sys.exit(errCode)

