#!/usr/bin/env python3
import sys, re
from selenium import webdriver

SERVER = 'http://127.0.0.1:80/'
ADMIN_PORT = ':8801'
NGINX_PORT = ':8800'

# hTtP
start_line = re.match(r'^(\S+) /(\S*) HTTP/1.[01]$', input().strip())
if not start_line:
    sys.stdout.write('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n')
    exit()

method = start_line.group(1)
path = start_line.group(2)

headers = {}
for _ in range(16):
    header_line = input().strip()
    if not header_line:
        break
    header, content = header_line.split(': ', 1)
    header = header.lower()
    headers[header] = (headers[header] + ', ' if header in headers else '') + content

if 'host' not in headers:
    sys.stdout.write('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n')
    exit()

host = headers['host'].replace(ADMIN_PORT, NGINX_PORT)

if method != 'POST':
    sys.stdout.write(f'HTTP/1.1 302 Found\r\nConnection: close\r\nLocation: http://{host}/?awesome=not_n__i__c__e\r\n\r\n')
    exit()

url = SERVER + path
print('[+] visiting ' + url, file=sys.stderr)

with open('/flag.txt') as f:
    flag = f.read().strip()

options = webdriver.ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Chrome(options=options)

driver.get(SERVER + '404')
driver.add_cookie({
    'name': 'flag',
    'value': flag,
    'sameSite': 'Strict',
})

driver.get(url)
driver.quit()

sys.stdout.write(f'HTTP/1.1 302 Found\r\nConnection: close\r\nLocation: http://{host}/?awesome=n__i__c__e\r\n\r\n')
exit()
