#!/usr/bin/python3
# -*- coding: utf-8 -*-

# clean-notes: sort and clean the notes stored in notes.git
# Copyright © 2018 Mattia Rizzolo <mattia@debian.org>
# Licensed under WTFPL — http://www.wtfpl.net/txt/copying/

import argparse
from requests import codes as retcodes

from rblib.certs import Certs


def whoami():
    """
    debugging function: check whether auth succeed
    """
    certs = Certs.from_browser()
    with certs.requests() as req:
        res = req.get("https://nm.debian.org/api/whoami")
        print(res.text)


def send_req(args):
    certs = Certs.from_browser()
    with certs.requests() as req:
        res = req.get("https://tests.reproducible-builds.org/cgi-bin/schedule")
        ret = res.status_code
        if ret == retcodes.ok:
            print('Scheduling successful!')
            if args.debug:
                print(res.text)
        elif ret == retcodes.bad:
            print('Validation error!')
            print(res.headers['X-Error-Message'])
            if args.debug:
                print(res.text)
        elif ret == 520:
            print('Unknown error while scheduling, check the output below')
            print(res.text)
        else:
            raise ValueError('Unhandled status code {}'.format(ret))


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--check',
        help='check whether your client cert is ok',
        action='store_true',
    )
    parser.add_argument(
        '-d', '--debug',
        help='dump the text from the scheduler also when otherwise '
             'not needed.',
        action='store_true',
    )
    args, remote_args = parser.parse_known_args()
    if args.check:
        whoami()
    else:
        send_req(args)
