#!/usr/bin/env python3

import argparse
from datetime import datetime
import subprocess
import json

def build_json(field,path):
    return json.dumps({field:f"This is a sample json event sent to {path}","hecTest":"yes"})

def build_raw(path):
    return f"{datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%fZ')} nowhere This is a sample raw event sent to {path} hecTest=yes"

def test_hec(dtype,verbose,baseurl,path,data):
    url   = baseurl+path
    cmd   = ['curl','-k',url,'-H',f"Authorization: {args.token}",'-d',data]

    if verbose:
        print(f"Running command:")
        print(f">\t{cmd[0]} {cmd[1]} {cmd[2]} \\")
        print(f"\t{cmd[3]} {cmd[4]} \\")
        print(f"\t{cmd[5]} '{cmd[6]}'")
        print()
    else:
        print(f"Testing '{dtype}': '{path}'")

    result = subprocess.run(cmd,capture_output=True,text=True)
    #print("stderr")
    #print(result.stderr)
    print(f"\033[0;32mResult\033[0m: {result.stdout}")
    print("")

parser = argparse.ArgumentParser(
        prog='hectest',
        description='Send a set of test HEC message to a receiver, using a variety of endpoints')

parser.add_argument('-t', '--token', required=True,
                    help='token to use (required)')
parser.add_argument('-v', '--verbose', action='store_true',
                    help='print the curl commands for further debugging')
parser.add_argument('url',
                    help="base url to send to, example: 'https://host.com:10080'")

args = parser.parse_args()

# Run an array of hec tests
test_hec('json', args.verbose, args.url,             '/cribl/_bulk', build_json( '_raw',             '/cribl/_bulk'))
test_hec('json', args.verbose, args.url,      '/services/collector', build_json('event',      '/services/collector'))
test_hec('json', args.verbose, args.url,  '/services/collector/raw', build_json('event',  '/services/collector/raw'))
test_hec('json', args.verbose, args.url,'/services/collector/event', build_json('event','/services/collector/event'))

# Run an array of raw tests
test_hec( 'raw', args.verbose, args.url,             '/cribl/_bulk', build_raw(                     '/cribl/_bulk'))
test_hec( 'raw', args.verbose, args.url,  '/services/collector/raw', build_raw(           '/services/collector/raw'))

# Can't send raw to /services/collector
# test_hec(args.url,      '/services/collector', build_raw(               '/services/collector'))
