:
# Usage: trackback.sh source_URL target_URL
#
# Trackback sends an HTTP request to the server of the target URL
# to inform it that source_URL is an article that contains a link to
# target_URL.
#
# Author: Bert Bos <bert@w3org>
# Created: 29 June 2007
# Copyright 2007 W3C
# See http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231


# die -- print error message on stderr and exit
function die {
  echo $1 >&2
  exit 1
}


trap 'rm -f $TMP' 0
TMP=`mktemp` || die "Cannot create temporary file"

# The trackback spec says the title and excerpt are optional, but
# b2evolution doesn't accept trackbcks without at least one of them
# :-(
#
title=`curl -f -L -s $1 | normalize -x | pipe |\
 sed -e '1,/(title/d' -e '/)title/,$d' -e 's/^-//'`
[[ -z "$title" ]] && die "Could not find title of $1"

# Get the target URL and look for a trackback URL in the returned
# page. This assumes the RDF looks like the sample in the trackback
# spec and also assumes there is only one such URL on the page. 
# (Asking a trackback client to parse RDF, when all it needs is one
# URL, what a stupid idea!)
#
curl -f -L -s "$2" >$TMP || die "Cannot find $2"
trackbackurl=`sed -n -e '/trackback:ping/{s/.*="//;s/".*//;p;q;}' $TMP`
[[ -z "$trackbackurl" ]] && die "Sorry, failed to find trackback URL"

# Send a trackback to the URL we just found.
#
domain="${trackbackurl##http://}"
domain="${domain%%/*}"
domain="${domain%%:*}"
port="${trackbackurl##http://}"
port="${port%%/*}"
port="${port#$domain}"
port="${port#:}"
port="${port:-80}"
path="/${trackbackurl#http://*/}"

url="${1//\%/%25}"
url="${url//&/%26}"
title="${title//\%/%25}"
title="${title//&/%26}"
title="${title//+/%2b}"
title="${title// /+}"
request="url=$url&title=$title"
length=`echo -e "$request\c" | wc -c`

echo -e "POST $path HTTP/1.1\r\n\
Host: $domain\r\n\
Content-Type: application/x-www-form-urlencoded; charset=utf-8\r\n\
Content-Length: $length\r\n\
\r\n\
$request\c" | nc $domain $port

echo
