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

# This file is part of Cockpit.
#
# Copyright (C) 2015 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <http://www.gnu.org/licenses/>.

import argparse
import datetime
import sys

sys.dont_write_bytecode = True

from common import testinfra

def httpdate(dt):
    """Return a string representation of a date according to RFC 1123
    (HTTP/1.1).

    The supplied date must be in UTC.

    From: http://stackoverflow.com/a/225106

    """
    weekday = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()]
    month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
             "Oct", "Nov", "Dec"][dt.month - 1]
    return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (weekday, dt.day, month,
        dt.year, dt.hour, dt.minute, dt.second)

def main():
    parser = argparse.ArgumentParser(description='Test GitHub rate limits')
    opts = parser.parse_args()

    # in order for the limit not to be affected by the call itself,
    # use a conditional request with a timestamp in the future

    future_timestamp = datetime.datetime.utcnow() + datetime.timedelta(seconds=3600)

    github = testinfra.GitHub()
    headers = { 'If-Modified-Since': httpdate(future_timestamp) }
    response = github.request("GET", "git/refs/heads/master", "", headers)
    sys.stdout.write("Rate limits:\n")
    for entry in ["X-RateLimit-Limit", "X-RateLimit-Remaining", "X-RateLimit-Reset"]:
        entries = filter(lambda t: t[0].lower() == entry.lower(), response['headers'].items())
        if entries:
            if entry == "X-RateLimit-Reset":
                try:
                    readable = datetime.datetime.utcfromtimestamp(float(entries[0][1])).isoformat()
                except:
                    readable = "parse error"
                    pass
                sys.stdout.write("{0}: {1} ({2})\n".format(entry, entries[0][1], readable))
            else:
                sys.stdout.write("{0}: {1}\n".format(entry, entries[0][1]))

if __name__ == '__main__':
    sys.exit(main())
