#!/usr/bin/env python

import json
import os
import re
import requests
from argparse import ArgumentParser
import sys
import ntpath
import time

from animus.LogParsers import *

BASE_URI = 'https://api.animus.io'

def main():

    CONFIG_FILE = os.path.expanduser('~/.animus.cfg')

    # Parse arguments
    args = parseArgs()

    if args.configure is True:
        try:
            config = configureCli(CONFIG_FILE)
            print('Omni Reduce has been successfully configured.')
            exit()

        # If we can't get our key, pitch an error
        except (AnimusAPIUnavailable, AnimusException) as e:
            sys.stdout.flush()
            sys.stderr.write('[+] {ERROR}'.format(ERROR=e))
            exit()

    # Load the configuration
    #
    # Config varialbles should be:
    #    API_KEY
    #    BASE_URI
    
    # If we don't have a config file, we need to build one
    if os.path.isfile(CONFIG_FILE):
        with open(CONFIG_FILE) as f:
            config = json.load(f)
    else:
        sys.stderr.write('[+] Please run ./omni-reduce --configure to configure your account\n')
        exit()

    # If we have a file
    if args.filename is not None:
        f = open(args.filename, 'r')
        filename = args.filename

    # If we have input on stdin
    else:
        f = sys.stdin
        filename = ''

    lines = f.readlines()

    # Close the file if we have one
    if args.filename is not None:
        f.close()

    # Our classes can throw exceptions. We should catch them.
    try:

        # Lets get the right type of log file
        if args.type is None:
            # If they idn't specify a type, let's guess
            try:
                args.type = guessType(lines, ntpath.basename(filename))
            except AnimusException as e:

                # TODO: If we have a port in this block, we should try generic with the ports and protos specified
                if args.port is not None:
                    args.type = 'generic'
                else:
                    sys.stderr.write('[+] {ERROR}\n'.format(ERROR=e))
                    exit()

        if args.type == 'auth':
            logfile = AnimusAuthLog(lines, config['API_KEY'], config['BASE_URI'])
        elif args.type == 'http':
            logfile = AnimusHttpLog(lines, config['API_KEY'], config['BASE_URI'])
        elif args.type == 'generic':

            # Make sure the port is properly formatted
            if args.ports is not None and re.search("^\d+:(tcp|udp|TCP|UDP)(\s\d+:(tcp|udp|TCP|UDP))*$", " ".join(args.ports)):
                logfile = AnimusGenericLog(lines, args.ports, config['API_KEY'], config['BASE_URI'])
            else:
                raise AnimusException('Generic mode requires a port and protocol be specified with the -p flag.')

    # If the API is unavailable, we should fail somewhat gracefully
    except AnimusAPIUnavailable as e:
        sys.stderr.write('[+] {ERROR}\n'.format(ERROR=e))
        exit()

    # Catch some general errors such as flag misconfiguration
    except AnimusException as e:
        sys.stderr.write('[+] {ERROR}\n'.format(ERROR=e))
        exit()

    # If we couldn't parse it, try it as generic with a sane set of ports
    except AnimusLogParsingException as e:

        sys.stderr.write('[+] Could not parse your logfile. Attempting to parse it as a generic file.\n')

        if e.type == 'auth':
            ports = ["22:tcp"]
        elif e.type == 'http':
            ports = ["80:tcp", "8080:tcp", "443:tcp", "8443:tcp"]
        else:
            sys.stderr.write('[+] Could not parse your logfile.\n'.format(ERROR=e))
            exit()

        try:
            logfile = AnimusGenericLog(args.filename, ports, config['API_KEY'], config['BASE_URI'])
        except AnimusLogParsingException:
            sys.stderr.write('[+] Could not parse your logfile, even after trying very hard.\n')
            exit()


    # Output the log data to the right place
    if not args.dryrun:
        output(logfile, args.shownoise, args.outfile)

    # Display stats, if appropriate
    if args.showstats or args.dryrun:
        showStats(logfile)
 
    # Report stats back to us
    try:
        # Make sure the user has not opted out
        if 'report_stats' in config and config['report_stats'] == True:
            reportStatistics(logfile, config['BASE_URI'], config['API_KEY'])

    # If we can't report stats, too bad for us I guess
    except AnimusAPIUnavailable as e:
        pass

################################g
# Description:
#   This function attempts to guess the type of log the user specified
#
# Params:
#   logfile - The log lines
#   baseName - The name of the file being analyzed
################################

def guessType(logfile, baseName):
    REGEX_HTTP = "^\[(?P<timestamp>.+)?\]\s\"(?P<request>.+?)\"\s(?P<responseCode>\d+)\s(?P<size>\d+)(?P<combinedFields>.*)"

    # First, we are going to try to guess the filetype by name
    if baseName == 'auth.log':
        sys.stderr.write('[+] Processing as an auth log.\n')
        return 'auth'
    if baseName == 'access.log':
        sys.stderr.write('[+] Processing as an http access log.\n')
        return 'http'

    # If we can't do that, we will read 10 lines in, then try to match with a regular expression
    logline = logfile[min(10, len(logfile)-1)]

    try:

        # See if it's http
        splitLine = logline.split()
        m = re.search(REGEX_HTTP, " ".join(splitLine[3:]))
        if m:
            sys.stderr.write('[+] Processing as an http access log.\n')
            return 'http'

        # See if it's auth
        try:
            # Try and make a timestamp from the beginning of the line
            if int(time.mktime(time.strptime(" ".join(splitLine[0:3]) + " " + "2017", "%b %d %H:%M:%S %Y"))) > 0:
                sys.stderr.write('[+] Processing as an auth log.\n')
                return 'auth'
        except Exception as e:
            pass

        # If we haven't returned by now, we can't figure out the type
        raise AnimusException("Unable to automatically identify the log type. Please specify a type with the -t flag.")
    except IOError as e:
        sys.stderr.write('[+] {ERROR}\n'.format(ERROR=e))
        exit()



################################g
# Description:
#   We would like to have high level statistics about the use of the tool.
#
# Params:
#   logfile - The file that was analyzed
#
################################

def reportStatistics(logfile, baseUri, api_key):

    API_ENDPOINT = "/va/stats"

    postData = {}

    # Total number of lines in the file
    postData['lines_analyzed'] = len(logfile.parsedLog)

    # Number of lines eliminated
    postData['lines_removed'] = len(logfile.noisyLogs)
    
    # Get up to 10 unhandled logs and report them
    postData['unhandled_logs'] = logfile.unhandledLogs[:min(10, len(logfile.unhandledLogs))]

    try:
        r = requests.post(baseUri + API_ENDPOINT, data = postData, headers={'Api_key': api_key})
    except requests.exceptions.ConnectionError as e:
        raise AnimusAPIUnavailable("The Animus API appears to be unavailable.")


    if r.status_code != 200:
        raise AnimusAPIUnavailable("Request failed and returned a status of: " + str(r.status_code))

################################
# Description:
#   If we have no configuration file, we need to configure the CLI and save the config as json
#
# Params:
#   configFile - The file to store the configuration in
#
# Returns:
#   config - The configuration object
################################

def configureCli(configFile):

    API_ENDPOINT = '/va/keygen'

    # The dict to return
    config = {}

    try:
        # See if they already have a registered API key
        haveAccount = prompt(
                    "Do you already have a registered API key? [y/N]", 
                    "Please respond (y)es or (n)o.", 
                    lambda v : re.search(r"(^((y|Y).*|(n|N).*))|^$", v))
    except EOFError as e:
        print('')
        raise AnimusException('Please run ./omni-reduce --configure\n')

    if haveAccount[:1].lower() == 'y':

        # TODO: Update the RE to match API key
        apiKey = prompt(
                    "Please enter your API key:", 
                    "Please enter a valid API key.", 
                    lambda v : re.search(r"^\w{64}", v))
        
        config['API_KEY'] = apiKey

    else:

        # Ask the user for their e-mail
        email = prompt(
                    "Please provide your email address:", 
                    "You must provide a valid email address.", 
                    lambda v : re.search(r"[^@]+@[^@]+\.[^@]+", v)) 

        # TODO: Make API call to the registration endpoint
        try:
            r = requests.post(BASE_URI + API_ENDPOINT, data = json.dumps({'email': email}))
        except requests.exceptions.ConnectionError as e:
            raise AnimusAPIUnavailable("The Animus API appears to be unavailable.")

        if r.status_code != 200:
            raise AnimusAPIUnavailable("Request failed and returned a status of: " + str(r.status_code))

        res = json.loads(r.text)

        if res['status'] == 'ok':
            config['API_KEY'] = res['api_key']
        else:
            raise AnimusAPIUnavailable(res['message'])
            

    config['BASE_URI'] = BASE_URI
    config['report_stats'] = True


    try:
        with open(configFile, 'w') as f:
            print('Storing Animus API key in ~/.animus.cfg')
            f.write(json.dumps(config))
    except Exception as e:
        exit('Unable to write confiuration file.')

    return config


################################
# Description:
#   Show the statistics for the recently parsed file
#
# Params:
#   logfile - The file that was reduced, which we want statistics for
################################

def showStats(logfile):

    # Total number of lines in the file
    totalSize = len(logfile.parsedLog)

    # Number of lines eliminated
    noiseSize = len(logfile.noisyLogs)

    # Size of the log file after reduction
    quietSize = len(logfile.quietLogs)

    sys.stderr.write('[+] {TOTAL_SIZE} lines were analyzed in this log file.\n'.format(TOTAL_SIZE=totalSize))
    sys.stderr.write('[+] {NOISE_SIZE} lines were determined to be noise by Animus.\n'.format(NOISE_SIZE=noiseSize))
    sys.stderr.write('[+] {QUIET_SIZE} lines were not determined to be noise by Animus.\n'.format(QUIET_SIZE=quietSize))

    # Format the percentage
    percent = "{0:0.01f}".format((int(quietSize) / float(totalSize))*100)

    sys.stderr.write('[+] The input file was reduced to {PERCENT}% of it\'s original size.\n'.format(PERCENT=percent))


################################
# Description:
#   Output the log data to the appropriate place. Typically stdout or a file
#
# Params:
#   logfile - The log that was analyzed
#   shownoise - Boolean for if we should show the noise rather than the reduced log file
#   outfile - The file we should write the output to
################################

def output(logfile, shownoise, outfile):

    if outfile:
        # Print to a file
        with open(outfile, 'w') as f:
            for log in logfile.reduce(shownoise):
                f.write(log + '\n')
        f.close()

    else:
        # Print to screen
        for log in logfile.reduce(shownoise):
            print log


################################
# Description:
#   Parses all the arguments for the CLI tool
#
# Returns:
#   The list of parsed arguments as a dict
################################

def parseArgs():
    parser = ArgumentParser()

    parser.add_argument('--type', '-t', help='Log type to analyze', 
            choices=['auth', 'http', 'generic'], type=str, action='store',
            required=False, dest='type')
        
    parser.add_argument('--noise', '-n', help='Print the noise from the file rather than reducing it',
            action='store_true', required=False, dest='shownoise')
    
    parser.add_argument('--out-file', '-o', help='Output file for the result',
            type=str, action='store', required=False, dest='outfile')

    parser.add_argument('--stats', '-s', help='Print statistics to STDERR from the reduction operation',
            action='store_true', required=False, dest='showstats')
    
    parser.add_argument('--dry-run', '-d', help='Don\'t output the reduced log file, only print possible reduction statistics to STDERR',
            action='store_true', required=False, dest='dryrun')

    parser.add_argument('--port', '-p', help='Port and protocol used by generic mode. Can be used multiple times. Should be of the form \"80:TCP\" or \"53:UDP\"',
            type=str, action='append', required=False, dest='ports')

    parser.add_argument('--configure', help='Configure Omni Reduce.',
            action='store_true', required=False, dest='configure')

    parser.add_argument('filename', help='Filename of log file to reduce',
            type=str, action='store', nargs='?')


    # TODO: Verify that all variable combinations are correct

    return parser.parse_args()

def prompt(message, errormessage, isvalid=lambda v: True):
    """Prompt for input given a message and return that value after verifying the input.

    Keyword arguments:
    message -- the message to display when asking the user for the value
    errormessage -- the message to display when the value fails validation
    isvalid -- a function that returns True if the value given by the user is valid
    """
    res = None
    while res is None:
        res = input(str(message)+' ')
        if not isvalid(res):
            print str(errormessage)
            res = None
    return res

if __name__ == '__main__':

    # Python 2/3 compatibility for user input
    try:
        input = raw_input
    except NameError:
        pass

    try:
        main()
    except (KeyboardInterrupt) as e:
        #sys.stderr.write('\n[+] Process terminated by user.\n')
        exit()
