#!/usr/bin/env python
import getopt
import sys
import os
import gettext
import base64
 
# First of all, we need to change the working directory to the w3af directory.
current_dir = os.getcwd()
script_dir = os.path.dirname(os.path.realpath(__file__)) or '.'
os.chdir(script_dir)

def back_to_current_dir():
    os.chdir( current_dir )

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

# Make sure that the output manager is started before doing anything else, since
# it is used by most w3af modules 
from core.ui.console.console_ui import ConsoleUI
import core.controllers.output_manager as om
try:
    om.out.set_output_plugins( ['console'] )
except Exception, e:
    print 'Something went wrong, w3af failed to start the output manager.'
    print 'Exception: "%s"' % e
    sys.exit(-9)

from core.controllers.profiling.cpu_usage import dump_cpu_usage
from core.controllers.misc.get_w3af_version import get_w3af_version


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

Usage:

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

Options:

    -h or --help
        Display this help message.

    -s <script_file> or --script=<script_file>
        Run <script_file> script.

    -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>
    
    -P <profile> or --profile-run=<profile>
        Run with the selected <profile> in batch mode
    
    -v or --version
        Show w3af's version

For more info visit http://w3af.org/
'''

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

def main():
    try:
        long_options = ['script=', 'help', 'version', 'no-update',
                        'force-update', 'profile=', 'commit=', 'profile-run']
        opts, _ = getopt.getopt(sys.argv[1:], "ehvs:nfp:P:", long_options)
    except getopt.GetoptError, e:
        # print help information and exit:
        usage()
        return -3
    script_file = None
    force_profile = None
    profile = None
    doupdate = None
    
    for o, a in opts:
        if o == "-e":
            # easter egg
            msg = 'R3JhY2lhcyBFdWdlIHBvciBiYW5jYXJtZSB0YW50YXMgaG9yYXMgZGUgZG'\
                  'VzYXJyb2xsbywgdGUgYW1vIGdvcmRhIQ=='
            om.out.information( base64.b64decode( msg ) )
        if o in ('-s', '--script'):
            script_file = a
        if o in ('-P', '--profile-run'):
            # selected profile
            force_profile = True
            profile = a
        if o in ('-p', '--profile'):
            # selected profile
            profile = a
        if o in ('-h', '--help'):
            usage()
            return 0
        if o in ('-v', '--version'):
            print get_w3af_version()
            return 0
        if o in ('-f', '--force-update'):
            doupdate = True
        elif o in ('-n', '--no-update'):
            doupdate = False
    
    commands_to_run = []
    if script_file is not None:
        try:
            fd = open( os.path.join(current_dir, script_file)  )
        except:
            om.out.error('Failed to open file : ' + script_file )
            sys.exit(2)
        else:
            commands_to_run = []
            for line in fd:   
                line = line.strip()
                if line != '' and line[0] != '#': # if not a comment..
                    commands_to_run.append( line )
            fd.close() 
    elif profile is not None:
        commands_to_run = ["profiles use %s %s" % (profile, current_dir)]
        if force_profile is not None:
            commands_to_run.append("start")
            commands_to_run.append("exit")

    console = ConsoleUI(commands=commands_to_run, do_upd=doupdate)
    
    if not console.accept_disclaimer():
        return -4
    
    return console.sh()


if __name__ == "__main__":
    exit_code = main()
    
    back_to_current_dir()
    dump_cpu_usage()
    
    sys.exit(exit_code)
    
