from functools import partial
from http.server import BaseHTTPRequestHandler, HTTPServer
from http.client import HTTPSConnection
from urllib import parse
import sys

SERVER = "sec-commerce.seclab.space"

class Server(BaseHTTPRequestHandler):

    def __init__(self, filepath, *args, **kwargs):
            self.filepath = filepath
            super().__init__(*args, **kwargs)


    # GET request handler 
    def do_GET(self):
        # retrieve the path from the HTTP request
        path = self.path
        # retrieve the headers from the HTTP request
        headers = self.headers
        #print("PATH: " + path)
        # retrieve the body from the HTTP request
        body = ""
        if(self.headers.get('content-length') != None):
            datalen = int(self.headers.get('content-length'))
            body = self.rfile.read(datalen)
        #print("This is the body for " + path)
        #print(body)
        # send an HTTP request to another server and get the response
        conn = HTTPSConnection(self.headers.get('host'))
        method = 'GET'
        conn.request(method, path, body, headers)
        # and get the response back 
        res = conn.getresponse()
        responseBody = res.read()
        conn.close()
        
        # set HTTP response status code and body
        self.send_response(res.status, responseBody)
        # set HTTP reponse headers
        for i in range(0, len(res.getheaders())):
            self.send_header(res.getheaders()[i][0], res.getheaders()[i][1])
        self.end_headers() 

        #get flag
        if(path == "/check"):
            #get flag from response
            flag = responseBody.decode()

            with open(self.filepath, "w") as file_stream:
                file_stream.write(flag)
            #exit program
            sys.exit(0)

    # POST request handler 
    def do_POST(self):
        # retrieve the path from the HTTP request
        path = self.path
        # retrieve the headers from the HTTP request
        headers = self.headers
        #print("PATH: " + path)
        # retrieve the body from the HTTP request
        body = ""
        if(self.headers.get('content-length') != None):
            datalen = int(self.headers.get('content-length'))
            body = self.rfile.read(datalen)
        #print("This is the body for " + path)
        #print(body)
        # send an HTTP request to another server and get the response
        conn = HTTPSConnection(self.headers.get('host'))
        method = 'POST'
        conn.request(method, path, body, headers)
        # and get the response back 
        res = conn.getresponse()
        responseBody = res.read()
        conn.close()
        
        # set HTTP response status code and body
        self.send_response(res.status, responseBody)
        # set HTTP reponse headers
        for i in range(0, len(res.getheaders())):
            self.send_header(res.getheaders()[i][0], res.getheaders()[i][1])
        self.end_headers() 

      
    # PUT request handler     
    def do_PUT(self):
        # retrieve the path from the HTTP request
        path = self.path
        # retrieve the headers from the HTTP request
        headers = self.headers
        #print("PATH: " + path)
        # retrieve the body from the HTTP request
        body = ""
        if(self.headers.get('content-length') != None):
            datalen = int(self.headers.get('content-length'))
            body = self.rfile.read(datalen)
        #print("This is the body for " + path)
        #print(body)
        # send an HTTP request to another server and get the response
        conn = HTTPSConnection(self.headers.get('host'))
        method = 'PUT'
        conn.request(method, path, body, headers)
        # and get the response back 
        res = conn.getresponse()
        responseBody = res.read()
        conn.close()
        
        # set HTTP response status code and body
        self.send_response(res.status, responseBody)
        # set HTTP reponse headers
        for i in range(0, len(res.getheaders())):
            self.send_header(res.getheaders()[i][0], res.getheaders()[i][1])
        self.end_headers() 


def run_server(filepath):
    handler = partial(Server, filepath)
    httpd = HTTPServer(('', 8080), handler)
    httpd.serve_forever()
    
if __name__ == "__main__":
    import os, sys, getopt
    def usage():
       print ('Usage:    ' + os.path.basename(__file__) + ' filepath ')
       sys.exit(2)
    # extract parameters
    try:
         opts, args = getopt.getopt(sys.argv[1:],"h",["help"])
    except getopt.GetoptError as err:
         print(err)
         usage()
         sys.exit(2)
    filepath = args[0] if len(args) > 0 else None
    for opt, arg in opts:
        if opt in ("-h", "--help"):
           usage()
    if (filepath is None):
        print('filepath is missing\n')
        usage()
    # run the command
    run_server(filepath)