#!/usr/bin/env python
# -*- coding: utf-8 -*-

from pymisp import PyMISP
from keys import misp_url, misp_key, misp_verifycert
import argparse
import os
import json


# Usage for pipe masters: ./last.py -l 5h | jq .


def init(url, key):
    return PyMISP(url, key, misp_verifycert, 'json')


def download_last(m, last, out=None):
    result = m.download_last(last)
    if out is None:
        if 'response' in result:
            print(json.dumps(result['response']))
        else:
            print('No results for that time period')
            exit(0)
    else:
        with open(out, 'w') as f:
            f.write(json.dumps(result['response']))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Download latest events from a MISP instance.')
    parser.add_argument("-l", "--last", required=True, help="can be defined in days, hours, minutes (for example 5d or 12h or 30m).")
    parser.add_argument("-o", "--output", help="Output file")

    args = parser.parse_args()

    if args.output is not None and os.path.exists(args.output):
        print('Output file already exists, abord.')
        exit(0)

    misp = init(misp_url, misp_key)

    download_last(misp, args.last, args.output)

[((15, 11, 15, 52), 'pymisp.PyMISP', 'PyMISP', ({(15, 18, 15, 21): 'url', (15, 23, 15, 26): 'key', (15, 28, 15, 43): 'misp_verifycert', (15, 45, 15, 51): '"""json"""'}, {}), "(url, key, misp_verifycert, 'json')", False, 'from pymisp import PyMISP\n'), ((31, 13, 31, 96), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (), '', False, 'import argparse\n'), ((37, 35, 37, 62), 'os.path.exists', 'os.path.exists', ({(37, 50, 37, 61): 'args.output'}, {}), '(args.output)', False, 'import os\n'), ((22, 18, 22, 48), 'json.dumps', 'json.dumps', ({(22, 29, 22, 47): "result['response']"}, {}), "(result['response'])", False, 'import json\n'), ((28, 20, 28, 50), 'json.dumps', 'json.dumps', ({(28, 31, 28, 49): "result['response']"}, {}), "(result['response'])", False, 'import json\n')]