#!/usr/bin/python3

import os
import sys

import urllib.request
import json

#urllib.request.urlcleanup()
request = urllib.request.Request('http://autopkgtest.ubuntu.com/static/running.json')
request.add_header('Cache-Control', 'max-age=0')
with urllib.request.urlopen(request) as response:
    data = response.read()
    jobs = json.loads(data.decode('utf-8'))


running = []
for pkg in jobs:
    for handle in jobs[pkg]:
        for series in jobs[pkg][handle]:
            for arch in jobs[pkg][handle][series]:
                jobinfo = jobs[pkg][handle][series][arch]
                triggers = ','.join(jobinfo[0].get('triggers', '-'))
                ppas = ','.join(jobinfo[0].get('ppas', '-'))
                time = jobinfo[1]
                if time < 60:
                    time = "{0:5}s".format(time)
                else:
                    time = int(time / 60)
                    time = "{0:3}:{1:02}".format(int(time / 60), int(time % 60))
                try:
                    running.append((jobinfo[1], "R     {6:6} {0:30} {5:10} {1:8} {2:8} {3:31} {4}".format(pkg, series, arch, ppas, triggers, '-', time)))
                except BrokenPipeError:
                    sys.exit(1)

for (time, row) in sorted(running, reverse=True):
    print(row)
                    
request = urllib.request.Request('http://autopkgtest.ubuntu.com/queues.json')
request.add_header('Cache-Control', 'max-age=0')
with urllib.request.urlopen(request) as response:
    data = response.read()
    queues = json.loads(data.decode('utf-8'))

    for origin in queues:
        for series in queues[origin]:
            for arch in queues[origin][series]:
                n = 0
                for key in queues[origin][series][arch]:
                    (pkg, json_data) = key.split(maxsplit=1)
                    jobinfo = json.loads(json_data)

                    triggers = ','.join(jobinfo.get('triggers', '-'))
                    ppas = ','.join(jobinfo.get('ppas', '-'))

                    n = n + 1
                    try: 
                        print("Q{5:04d} {7:>6} {0:30} {6:10} {1:8} {2:8} {3:31} {4}".format(pkg, series, arch, ppas, triggers, n, origin, '-:--'))
                    except BrokenPipeError:
                        sys.exit(1)

        #                 /Running for:/ { printf("%-30s %-8s %-8s%-31s%s\n", pkg, release, arch, ppas, triggers); next }

