#!/bin/python3

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

import subprocess as sp
import cgi 
import json

result=""

query = cgi.FieldStorage()

img_name = query.getvalue("image_name")

list_all = query.getvalue("list_all")

all_status = 1


status = 1

if img_name != None:
    cmd=f"sudo docker image ls | grep {img_name.split(':')[0] }"
    status,output = sp.getstatusoutput(cmd)


if list_all == "on":

    cmd = f"sudo docker image ls"

    all_status,all_output = sp.getstatusoutput(cmd)


if all_status == 0:
    print("<pre>")
    for row in all_output.split("\n"):
        print("<h4>" + row + "</h4>")
    print("</pre>")

if status == 0:
        print("<h4>" + img_name +" image is present </h4>")

        print("<pre><h3>" + output  + "</h3></pre>")

print("<h4>json output</h4>")
print()
if status == 0:
    result =json.dumps({
             "image" : str(img_name),
             "status" : "present"
             },indent=4)
else:
    if img_name is None:
        output="Please enter the image name"
    else:
        output ="not present"

    result =json.dumps({
    "image" : str(img_name),
    "status": "absent",
    "reason" : str(output)
            },indent=4)

print(result)

    






