#!/usr/bin/env python3
#
# Serve a site under the ./public folder.
#
# Useful for testing the results of a build process.
#

import os
import http.server
import socketserver

PORT    = 5000
Handler = http.server.SimpleHTTPRequestHandler
public  = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, 'public')

class MyTCPServer(socketserver.TCPServer):
    """
    Avoid the "Address already in use" issue by using SO_REUSEADDR.

    https://stackoverflow.com/questions/10085996/shutdown-socketserver-serve-forever-in-one-thread-python-application
    https://stackoverflow.com/questions/6380057/python-binding-socket-address-already-in-use/18858817
    """
    def server_bind(self):
        import socket
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(self.server_address)

    def handle_error(self, request, client_address):
        print(request)

def serve():
    if not os.path.exists(public):
        try:
            os.makedirs(public, mode=0o755)

        except Exception:
            print('No such folder ' + public)
            exit(1)

    os.chdir(public)

    with MyTCPServer(("", PORT), Handler) as httpd:
        try:
            print("Serving at port", PORT)
            httpd.serve_forever()

        except KeyboardInterrupt:
            httpd.shutdown()

if __name__ == "__main__":
    serve()
