import bottle
import os.path
import subprocess

HOST = "0.0.0.0"
PORT = 8080

# this script runs a small webserver on HOST:PORT that return the class course
# all assets are stored in ./resources and available for download
# the main page can be visited by going to "http://HOST:PORT/puredata"
# the bottle framework is needed to run this script
# you can install it with "python3 -m pip install --user bottle"

@bottle.route("/<filename>")
def index(filename):
    if filename == "puredata":
        return bottle.static_file("index.html", root="./")
    else:
        return bottle.static_file(filename, root="./")

@bottle.route("/resources/<filename>")
def resources(filename):
    return bottle.static_file(filename, root="resources")

def main():
    if os.path.isfile("index.html"):
        print("index.html is present, we can run!")
        bottle.run(host=HOST, port=PORT)
    else:
        print("index.html not found, will generate it now with pandoc")
        status = subprocess.call(["pandoc", "puredata.md", "-o", "index.html"])
        if status is 0:
            print("success... will run now!")
            bottle.run(host=HOST, port=PORT)


if __name__ == "__main__":
    main()
