import BaseHTTPServer, SimpleHTTPServer
import subprocess, shlex
import ssl
import time
import os
from optparse import OptionParser

port = 4443

execfile('./variables.py')

parser = OptionParser()
parser.add_option('-p', "--port", dest='port', help='Run HTTPS server on PORT', metavar='PORT')

(options, args) = parser.parse_args()

print('Running SelfKit v' + skp['SKVersion'] + ' (build ' + skp['SKBuild'] + ') web server on port ' + port.__str__() + '...')

if not os.path.exists("./server.pem"):
    print './server.pem does not exist. Creating...'
    command = 'openssl req -new -x509 -keyout ./server.pem -out ./server.pem -days 3650 -nodes -subj "/C=/ST=/L=/O=/CN=localhost"'
    print (command)
    args = shlex.split(command)
    p = subprocess.call(args)
    print ('Running web server...')

class SKWebHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        if (self.path == '/' or self.path == ''): self.path = '/index.html'
        if os.path.exists('content' + self.path):
            f = open('content' + self.path)
            
            page = f.read()
            page = replaceVariables(page)
            
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.send_header('X-SelfKit-Version', skp['SKVersion'])
            self.end_headers()
            self.wfile.write(page)
            return
        else:
            self.send_response(400)
            self.send_header('X-SelfKit-Version', skp['SKVersion'])
            self.end_headers()
            self.wfile.write('<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL ' + self.path + ' was not found on this server.</p></body></html>')
            
    def 
(self, format, *args):
        return

if os.path.exists('./server.pem'):
    httpd = BaseHTTPServer.HTTPServer(('localhost', port), SKWebHandler)
    httpd.socket = ssl.wrap_socket(httpd.socket, certfile='server.pem', server_side=True)
    httpd.serve_forever()

log_message