#!/bin/python3

print("content-type: text/html")
print()

import subprocess as sp
import cgi 
import json
import datetime

query = cgi.FieldStorage()


con_name = query.getvalue("con_name")

all_containers = query.getvalue("all_containers")

result=""


status,output = sp.getstatusoutput(f'sudo docker stats {con_name}  --no-stream')
output= "\n"+output+"\n"

if all_containers == "on":
	all_status,all_output = sp.getstatusoutput(f'sudo docker stats --no-stream')
	
	print('<h2> STATUS OF ALL CONTAINERS RUNNING </h2>')
	all_output = all_output.split("\n")

	for container in all_output:

		print("<pre><h3>"+container+"</h3></pre>")
print()
if con_name != None:
	if status == 0:
		print()		
		print(f'<h3>STATUS OF { con_name }</h3>\n')
		print("\n<pre><h3>"+ output +"</h3></pre>\n")
		print("<h5>JSON OUTPUT</h5>\n")
		result =json.dumps({
            "name" : str(con_name),
            "status":  output,
            'checked_at': str(datetime.datetime.now())
             },indent=4)
	else:
		result =json.dumps({
    "name" : str(con_name),
    "status": "error",
    'tried_at': str(datetime.datetime.now()),
    "reason" : str(output)
            },indent=4)

	print(result)

    






