#!/bin/bash
dir=/www/sam.nipl.net/preview
site_url="http://sam.nipl.net"
debug() {
	return
	text_plain
	echo "$@"
}
cd "$dir"
text_plain() {
	if [ -z "$text_plain" ]; then
		echo "Content-Type: text/plain"
		echo ""
	fi
	text_plain=1
}
params=${REQUEST_URI#$SCRIPT_NAME/}
title=`echo ${params%%;*} | sed 's/%20/ /g'`  # dodgy!! need to rewrite in perl or C
url=${params#*;}
url=${url##/}
url=${url%.html}
local=${url/:\/\//\/}
debug "$url"
debug "$local"
if [ -d "$local" ]; then
	local=local/index.html
fi
if [ ! -e "$local" ]; then
	wget -q -c --force-directories --protocol-directories "$url"
fi
if [ -d "$local" ]; then
	local=local/index.html
fi
if [ ! -f "$local" ]; then
	debug "file not found"
	exit 1
fi
mime=`file -b -i "$local"`
debug "$mime"
preview=$local.png
preview_url="$site_url/preview/$preview"
debug "$preview"
debug "$preview_url"
if [ ! -e "$preview" ]; then
	case "$mime" in
	application/pdf*)
		pdftoppm -f 1 -l 1 -scale-to 1024 -png "$local" "$preview"
		mv $local.png-*.png "$local.png"
	esac
fi

if [ -e "$preview" ]; then
	case "$HTTP_USER_AGENT" in
	facebookexternalhit*|*)
		echo "Content-Type: text/html"
		echo ""
		echo '<!DOCTYPE html>'
		echo '<meta property="og:title" content="'"$title"'" />'
		echo '<meta property="og:image" content="'"$preview_url"'" />'
		exit 0
	esac	
fi

echo "Location: $url"
echo ""

# set
