#!/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)

usage_doc = '''
w3af - Web Application Attack and Audit Framework

Usage:

    ./w3af_console -h
    ./w3af_console -f
    ./w3af_console [-s <script_file>]

Options:

    -h or --help
        Display this help message.

    -n or --no-update
        No update check will be made when starting. This option takes 
        precedence over the 'auto-update' setting in 'startup.conf' file.
     
    -f or --force-update
        An update check will be made when starting. This option takes 
        precedence over the 'auto-update' setting in 'startup.conf' file.
    
    -p <profile> or --profile=<profile>
        Run with the selected <profile>

For more info visit http://w3af.sourceforge.net/
'''    

def usage():
    om.out.information(usage_doc)

def main():
    try:
        long_options = ['help', 'no-update', 'force-update', 'profile=']
        opts, args = getopt.getopt(sys.argv[1:], "ehnfp:", long_options)
    except getopt.GetoptError:
        # print help information and exit:
        usage()
        return -3
    profile = None
    doupdate = None
    for o, a in opts:
        if o in ( "-e"  ):
            # easter egg
            import base64
            om.out.information( base64.b64decode( 'R3JhY2lhcyBFdWdlIHBvciBiYW5jYXJtZSB0YW50YXMgaG9yYXMgZGUgZGVzYXJyb2xsbywgdGUgYW1vIGdvcmRhIQ==' ) )
        if o == "-s":
            scriptFile = a
        if o in ('-p', '--profile'):
            # selected profile
            profile = a
        if o == "-h":
            usage()
            return 0
        if o in ('-f', '--force-update'):
            doupdate = True
        elif o in ('-n', '--no-update'):
            doupdate = False
    

    # go with GTK, but first check about DISPLAY environment variable
    if sys.platform != "win32":
        display = os.getenv("DISPLAY")
        if not display:
            om.out.error("The DISPLAY environment variable is not set! You can not use any graphical program without it...")
            return -1
    import core.ui.gtkUi.main
    core.ui.gtkUi.main.main(profile, doupdate)

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

