#!/usr/bin/env python3

from http.server import BaseHTTPRequestHandler, HTTPServer
import sqlite3
import time

class MyServer(BaseHTTPRequestHandler):
   def do_GET(self):
      self.send_response(200)
      self.send_header("Content-type", "text/html")
      self.end_headers()
      self.wfile.write(bytes("<html><head><title>Status</title></head>", "utf-8"))
      self.wfile.write(bytes("<table><tr><td>Host</td><td>Status</td></tr>", "utf-8"))

      for row in self.cursor.execute('SELECT host, status FROM log'):
         host, status = row
         self.wfile.write(bytes("<tr><td>%s</td><td>%s</td></tr>" % \
                         (host, "Up" if status==0 else "Down"), "utf-8"))

      self.wfile.write(bytes("</table>", "utf-8"))
      

def main():
   conn = sqlite3.connect('log.db')
   cursor = conn.cursor()
   addrinfo = ("localhost", 9000)

   MyServer.cursor = cursor
   myServer = HTTPServer(addrinfo, MyServer)

   print(time.asctime(), "Server Starts - %s:%s" % addrinfo)

   try:
      myServer.serve_forever()
   except KeyboardInterrupt:
      pass

   myServer.server_close()
   print(time.asctime(), "Server Stops - %s:%s" % addrinfo)

if __name__ == "__main__":
   main()
