#!/usr/bin/env sh
# Serve a local directory via HTTP (via socat) with or without SSL
#
# The -H flag provides server-side support for the HTML5 history API. If an
# incoming request is requsting an HTML document, all paths will resolve to the
# given document. Other requests are unaffected.
#
# Usage:
#
#     httpdir
#     httpdir -p 8000
#     httpdir -s
#     httpdir -H index.html

NAME=$(basename "$0")

HTTP_METHOD=''
HTTP_PATH=''
HTTP_VERSION=''

fnmatch () { case "$2" in $1) return 0 ;; *) return 1 ;; esac ; }

rep() {
    local status="${1:?Status is required.}"
    shift 1

    printf '%s %s %s\n' "$status" "$HTTP_METHOD" "$HTTP_PATH" 1>&2
    printf 'HTTP/1.0 %s\r\n' "$status"
    for hdr in "$@"; do
        printf '%s\r\n' "$hdr"
    done
    printf '\r\n'
}

http() {
    local crlf=$(printf '\r\n')
    local accept_compressed=0

    read -r HTTP_METHOD HTTP_PATH HTTP_VERSION
    while IFS=": " read -r hdr val; do
        # stdin never closes in a socat exec so stop after the headers end.
        [ "$hdr" = "$crlf" ] && break

        case "$hdr" in
            Accept-Encoding) accept_compressed=1;;
            Accept)
                if $(printf '%s\n' "$val" | grep -iq 'text/html'); then
                    accept_html=1
                fi;;
        esac
    done

    if [ "$HTTP_PATH" = '/favicon.ico' ]; then
        rep '200 OK'
        exit
    fi

    if [ -n "$accept_html" -a -n "$HTML5OVERRIDE" ]; then
        local rpath="$HTML5OVERRIDE"
    else
        local rpath="$PWD$HTTP_PATH"
    fi

    if fnmatch '*..*' "$rpath"; then
        rep '400 Bad Request'
        exit
    fi

    # Remove query strings.
    rpath="${rpath%%\?*}"

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

    if [ -d "$rpath" ]; then
        local bpath="${rpath##$PWD}"
        local bpath="${bpath%/}"
        local base="//localhost:${SOCAT_SOCKPORT}${bpath}"
        rep '200 OK'
        tree "$rpath" \
            -H "$base" \
            -a \
            -h -F -D \
            -L 1 -x -i \
            -T "$base"
        exit
    fi

    if [ -r "$rpath" ]; then
        local ctype=""
        case "$rpath" in
            *.css) ctype='text/css';;
            *.js) ctype='application/javascript';;
            *.mjs) ctype='application/javascript';;
            *.json) ctype='application/json';;
            *) ctype="$(file -L -b --mime-type "$rpath")";;
        esac

        local content_encoding
        if [ "$accept_compressed" -eq 1 ] && [ -r "${rpath}.gz" ]; then
            content_encoding="Content-Encoding: gzip"
            rpath="${rpath}.gz"
        fi

        local clen="$(wc -c < "$rpath")"
        local cmod="$(date -r "$rpath" +'%a, %d %b %Y %T %Z')"

        rep '200 OK' \
            "Content-Type: ${ctype}" \
            "Content-Length: ${clen}" \
            "Last-Modified: ${cmod}" \
            ${content_encoding:+"$content_encoding"}
        cat "$rpath"
        exit
    fi

    rep '404 Not Found'
    exit
}

mk_cert() {
    openssl req -x509 \
        -newkey rsa:4096 \
        -days 365 \
        -nodes \
        -subj "/C=US/ST=Utah/L=Ogden/O=ACME, Inc./OU=Org/CN=localhost" \
        -keyout "${TMPDIR-/tmp}/${NAME}.key" \
        -out "${TMPDIR-/tmp}/${NAME}.crt" \
        2>/dev/null
}

main() {
    local opt
    local OPTIND
    local OPTARG
    local listen="TCP-LISTEN"
    local port="8000"
    local ssl=""

    while getopts hp:sH: opt; do
        case $opt in
        h) awk 'NR == 1 { next } /^$/ { exit } { print substr($0, 3) }' "$0"
           exit;;
        p) port="$OPTARG";;
        s) mk_cert;
            ssl=",cert=/tmp/${NAME}.crt,key=/tmp/${NAME}.key,verify=0";
            listen="OPENSSL-LISTEN";
            ;;
        H) export HTML5OVERRIDE="$OPTARG";;
        esac
    done
    shift $(( OPTIND - 1 ))

    if [ $# -eq 0 ]; then
        printf '%s on port %s\n' "$listen" "$port"
        socat "${listen}:${port},fork,reuseaddr${ssl}" EXEC:"${0} http"
    else
        "$1" "$@"
    fi
}

# set -x
main "$@"
