#!/usr/local/bin/bash
# Copyright (c) 2008, Brian Hetro <whee@smaertness.net>
PATH=/usr/local/bin:$PATH
shopt -s extglob
if test -z "${QUERY_STRING}"
then
INPUT="$1"
REMOTE_ADDR="localhost"
else
INPUT="${QUERY_STRING}"
fi
text_html() {
echo "Content-type: text/html"
}
text_plain() {
echo "Content-type: text/plain"
}
location() {
echo "Location: $1"
}
end_header() {
echo
}
output_redirect() {
uri="$1"
test "${uri}" || return
text_html
location "${uri}"
end_header
cat <<EOF
<html><head>
<meta http-equiv="REFRESH" content="0;${uri}">
</head></html>
EOF
}
output_index_page() {
text_html
end_header
cat <<EOF
<html><head><title>URI shortening</title></head>
<body>
<p>Welcome to a URI shortening service. To obtain a shortened URI,
enter this in your address bar:
<pre>http://${SERVER_NAME}${SCRIPT_NAME}?<i>[URI to shorten]</i></pre>
</p>
<p>For example, <pre><i>http://${SERVER_NAME}${SCRIPT_NAME}?http://example.com</i></pre></p>
<p>The URI you receive redirects to the URI you have provided.</p>
<hr />
This service is <a href="http://github.com/whee/giturl/tree/master">open source</a>, powered by <a href="http://git.or.cz/">git</a>.
</body>
</html>
EOF
}
# If INPUT is a SHA1, git cat-file -p it. This is the URI, and we are done.
case "${INPUT}" in
+([0-9a-f]) )
output_redirect $(git cat-file -p "${INPUT}")
exit 0;;
"" )
output_index_page
exit 0;;
esac
# If INPUT is not a SHA1, assume it is a URI.
# To add a URI to our database:
# Get a blob hash for it. We will store this for VC purposes later, so write
# it too.
# 1. blob = echo -n URI | git hash-object -w --stdin
blob=$(echo -n "${INPUT}" | git hash-object -w --stdin)
blob_dir=$(echo "${blob}" | cut -c -2)
blob_rest=$(echo "${blob}" | cut -c 3-)
blob_file="${blob_dir}/${blob_rest}"
output_uri() {
blob="$1"
blob=$(echo "${blob}" | cut -c -10)
loc="http://${SERVER_NAME}${SCRIPT_NAME}?${blob}"
text_plain
end_header
echo "${loc}"
}
# 1a. Stat bl/ob_SHA1. If the blob is there, output the link referencing it.
# The URI is already tracked.
if test -f "${blob_file}"
then
output_uri "${blob}"
exit 0
fi
# Create a file with the URI as its contents.
# 2. echo -n URI > bl/ob_SHA1
test -d "${blob_dir}" || mkdir "${blob_dir}"
echo -n "${INPUT}" > "${blob_file}"
# Stage the new file.
# 3. git add bl/ob_SHA1
git add "${blob_file}"
# And commit it with as much as identifying information as possible.
# 4. GIT_AUTHOR=ip-address git commit -m 'Add URI\nUSER-AGENT\nMORE_IDENT'
GIT_AUTHOR_NAME="${REMOTE_ADDR}"
GIT_AUTHOR_EMAIL="gurl@${SERVER_NAME}"
export GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL
git commit -qm "${INPUT}
${HTTP_USER_AGENT}"
# Finally, give the link to the client.
output_uri "${blob}"