#!/bin/bash
# Name:    checksum-cgi
# Notes:   Make sure "md5" or "md5sum" is an available command in OS
#

# disable filename globbing
set -f
# debug output
#set -x


# create a header for our HTML response
echo "Content-type: text/plain; charset=iso-8859-1"
echo

# 'snip' the filename from the HTML parsed QUERY_STRING
export FilenameBeforeEncoded=`echo "$QUERY_STRING" | sed -n 's/^.*filename=\([^&]*\).*$/\1/p'` 
export Filename=$(echo -e `echo $FilenameBeforeEncoded | sed 's/%20/\\ /g;s/+/\\ /g;s/%/\\\\x/g'`)
# test the command of calculating MD5 sum
MD5_CMD=
[ -z "$MD5_CMD" ] && type md5 >/dev/null 2>&1 && MD5_CMD="md5 \"$Filename\" | awk -F ' = ' '{ print \$2 }'"
[ -z "$MD5_CMD" ] && type md5sum >/dev/null 2>&1 && MD5_CMD="md5sum \"$Filename\" | awk '{ print \$1 }'"
[ -z "$MD5_CMD" ] && {
    echo "ERROR: No proper command found to calculate MD5 sum."
    exit 1
}

# Calculate the md5 checksum
eval $MD5_CMD