#!/bin/bash

# This is a web server. To use it, execute it without arguments at the
# root location of the website file hierarchy. It deals with html and
# cgi files and automatically adds "index.html" for requests to
# directories. Note that this pierce of code is highly unsecure and
# that it would be *insane* to use it as a public web server.

# Written and (C) by Francois Fleuret. Under a "do whatever you want
# with it, I don't care" licence. Contact <francois.fleuret@idiap.ch>
# for comments.

SERVER_ID="Bash Web Server/1.0"

case $1 in

    "") # Starting server
        while [ $? -eq 0 ]; do
            nc -lp 8080 -c "$0 client"
        done
        ;;

    client) # Handling a connection

        until [[ ${LINE} == "" ]]; do
            read -t 10 -r LINE
            if [[ -z $LINE ]]; then
                exit 0
            elif [[ $LINE =~ ^GET\ *(/[^ ]*)\ HTTP ]]; then
                FILE="./"${BASH_REMATCH[1]}
            fi
        done

        if [[ ${FILE} =~ ^([^\?]*)\?(.*)$ ]]; then
            FILE=${BASH_REMATCH[1]}
            ARGS=${BASH_REMATCH[2]}
        fi

        if [[ -d "${FILE}" ]]; then
            FILE="${FILE}/index.html"
        fi

        if [[ ${FILE} =~ \.html|css$ ]] && [[ -f ${FILE} ]]; then
            echo "HTTP/1.0 200 OK"
            echo "Server: ${SERVER_ID}"
            echo "Content-Type: text/html"
            echo
            cat ${FILE}
        elif [[ ${FILE} =~ \.cgi$ ]] && [[ -x ${FILE} ]]; then
            echo "HTTP/1.0 200 OK"
            echo "Server: ${SERVER_ID}"
            ${FILE} ${ARGS}
        else
            echo "HTTP/1.0 404 Not Found"
            echo "Server: ${SERVER_ID}"
            echo "Content-Type: text/html"
            echo
            echo "<HTML>"
            echo "<HEAD><TITLE>Error 404 - Not Found</TITLE></HEAD>"
            echo "<BODY><H1>Error 404 - Not Found</H1></BODY>"
            echo "</HTML>"
        fi
        exit 0
        ;;

    *)
        echo "$0 [client]" 1>&2
        exit 1
        ;;

esac
