import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.HashMap;
import java.util.Scanner;
class httpserver{
    public static void main(String[] args)throws Exception{
        try(ServerSocket serverSocket=new ServerSocket()){
            HashMap<String,String> hashMap=new HashMap<>();
            if(1<args.length)try(Scanner scanner=new Scanner(args[1])){
                while(null!=scanner.findInLine("([^\\[\\]]+)\\[([^\\[\\]]*)"))hashMap.put(scanner.match().group(1),scanner.match().group(2));
            }
            serverSocket.setReuseAddress(true);
            serverSocket.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(),8080));
            for(;;)try(Socket socket=serverSocket.accept();Scanner scanner=new Scanner(socket.getInputStream(),"utf-8");OutputStream outputStream=socket.getOutputStream()){
                if(null==scanner.findInLine("^.+ (.*/)([^?]*\\.([^?]*)|[^?]*)(?:\\?.*)? (.+)"))continue;
                String child=scanner.match().group(2),extension=scanner.match().group(3),statusCode="200";
                if(null==extension)child=(0==child.length()?"index":child)+"."+(extension="html");
                File file=new File(new File(args[0],scanner.match().group(1)),child);
                if(!file.exists()&&!(file=new File(args[0],(statusCode="404")+"."+(extension="html"))).exists())continue;
                try(FileChannel fileInputStreamChannel=new FileInputStream(file).getChannel();WritableByteChannel outputStreamChannel=Channels.newChannel(outputStream)){
System.out.println(file);
System.out.println(scanner.match().group(0));
                    long length=fileInputStreamChannel.size();
                    String res=scanner.match().group(4)+" "+statusCode+"\r\n"
                        +"Content-Type: "+hashMap.get(extension)+"\r\n"
                        +"Content-Length: "+length+"\r\n"
                        +"Connection: close\r\n"
                        +"\r\n";
System.out.println(res);
                    outputStream.write(res.getBytes("utf-8"));
                    long position=0;
                    try{
                        while(position<length)position+=fileInputStreamChannel.transferTo(position,length-position,outputStreamChannel);
                    }catch(Exception e){
System.out.println(e);
                    }
                }
            }
        }
    }
}