import socket
import os
import sys
import subprocess
import threading

def drop_privileges(uid=32767, gid=32766): #nobody, nogroup
    # Remove group privileges
    os.setgroups([])
    # Try setting the new uid/gid
    os.setgid(gid)
    os.setuid(uid)

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
		port = int(sys.argv[1]) 
except:
		port = 70
server_address = ('', port)
#bind socket to port
print("starting", server_address)
sock.bind(server_address)
os.chroot("/var/gopher")
drop_privileges()
sock.listen(1)

def serve_connection(conn):
	print("connection from", client_address)
	data = conn.recv(1000).decode()
	print("recieved", data)
	if data:
		while data != "" and (data[-1] == "\n" or data[-1] == "\r"):
			data = data[:-1]
		spl = data.split('\t', 1)
		p = "/" + spl[0]
		if os.path.isdir(p):
			p += "/gophermap"
		print("path is", p)
		try:
			if p[-10:] == "/guestbook":
				p += ".txt"
			if len(spl) != 1 and p[-14:] == "/guestbook.txt":
				f = open(p, "a")
				f.write(spl[1] + "\r\n")
				f.close()
				conn.sendall(b"iYour message has been put into the guestbook.		dread.life	1")
			f = open(p, "r")
			print("file is", f.name)
			conn.sendall(f.read().replace("\n", "\r\n").encode())
			f.close()
		except:
			conn.sendall(b"iError!		dread.life	1\n1Go home?	/	dread.life	70\n\n")
			print(sys.exc_info()[0])
	else:
		print("no data")
	conn.close()

while True:
	print("waiting")
	conn, client_address = sock.accept()
	t = threading.Thread(target = serve_connection, args = (conn,))
	t.start()

sock.close()