#!/bin/env python3

import re
import argparse
import requests
import sys


BASE_URL = 'https://www.bioqs.at'
URL = f'{BASE_URL}/ACM/faces/form/cms/portal/index.jsp'
ACTION_RE = re.compile(r'action="([^"]*)"')
HIDDEN_RE = re.compile(r'<input type="hidden" name="([^"]*)" .*?value="([^"]*)"')


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument('cert_nr', type=str)
    args = parser.parse_args()

    s = requests.Session()
    s.verify = False
    while True:
        try:
            r = s.get(f'{URL}?menu_sid=5002')
            uri = ACTION_RE.findall(r.text)[0]
            break
        except IndexError:
            pass
    hidden = {m[1]: m[2] for m in HIDDEN_RE.finditer(r.text)}

    while True:
        r = s.post(f'{BASE_URL}{uri}', data={
            'PartnerCertSearchForm:pcs_seqidall': args.cert_nr,
            'PartnerCertSearchForm:button_search': 'Suche starten...',
            'PartnerCertSearchForm_SUBMIT': '1',
            'javax.faces.ViewState': hidden['javax.faces.ViewState'],
        })

        if 'class="msg_error"' in r.text:
            print(f'404', file=sys.stderr)
            exit(1)

        p1 = r.text.find(f'>{args.cert_nr}<')
        p2 = r.text.find('id="', p1)
        p3 = r.text.find('"', p2 + 4)
        if p1 == -1 or p2 == -1 or p3 == -1:
            continue
        id = r.text[p2 + 4:p3]
        break

    r = s.post(f'{BASE_URL}{uri}', data={
        'PartnerCertSearchForm:_idcl': id,
        'PartnerCertSearchForm_SUBMIT': '1',
        'javax.faces.ViewState': hidden['javax.faces.ViewState'],
    })

    if 'Content-Disposition' in r.headers:
        dispo = r.headers['Content-Disposition']
        if 'filename="' in dispo:
            filename = dispo[dispo.find('filename="') + 10:dispo.rfind('"')]
            print(filename, file=sys.stderr)
    sys.stdout.buffer.write(r.content)


if __name__ == '__main__':
    main()
