#!/usr/bin/perl
# Simple TCP socket server using IO::Socket and IO::Select
use IO::Socket;
use IO::Select;
use warnings;
use strict;

my $port = $ARGV[0] || die "Usage: server_socket.pl <port>\n";

my $serverSocket = new IO::Socket::INET (LocalHost	=>	'10.1.4.29',
					 LocalPort	=>	$port,
					 Proto		=>	'tcp',
					 Listen		=>	5,
					 Reuse		=>	1,
					);
die "Socket could not be created: $!\n" unless $serverSocket;

my $socketList = new IO::Select();
$socketList->add($serverSocket);

print "Listening on port $port...\n";

my $httpRootDir = "/home/yakman/webRoot";
while (1) {
	my ($currentSocketList) = IO::Select->select($socketList, undef, undef, undef);
	foreach my $thisSocket (@$currentSocketList) {
		if ($thisSocket == $serverSocket) {
		# Connection to Server Socket
			my $newSocket = $thisSocket->accept();
			$socketList->add($newSocket);
		} else {
		# Connection to Client Socket

			# Service the client's request
			#    - read in the header lines
			#    - send back a webpage
			#    - close the connection

			my @buffer = ();

			for (1..8) {
				$_ = <$thisSocket>;
				push (@buffer, $_);
			}
			print @buffer;

			my $requestedFile = $httpRootDir . (split(/ /, $buffer[0]))[1];
			print "REQUESTED: $requestedFile\n";
			my $contentType;
			if ($requestedFile =~ /.txt/) { $contentType = "text/plain"; }
			elsif ($requestedFile =~ /.html/) { $contentType = "text/html"; }
			elsif ($requestedFile =~ /.jpg/) { $contentType = "image/jpeg"; }
			else { $contentType = "text/plain"; }

			open (FIN, $requestedFile);
			my @lines = <FIN>;
			close (FIN);

			print $thisSocket "HTTP/1.1 200 OK\n";
			print $thisSocket "Content-type: $contentType\n\n";
			print $thisSocket @lines;
			$socketList->remove($thisSocket);
			close($thisSocket);
		}
	}
}
