#!/bin/bash

# file that stores created tinyurls
tinyfile=~/tinyurls.txt
touch $tinyfile

# default: don't mail link
mailtiny=0
address=

# grab options ... only one so far is '-m', which mails the page
while getopts tm: opt
do
  case $opt in
      m)  mailtiny=1
	  address=$OPTARG
	  ;;
      t)  copytitle=1
	  ;;
      '?')      echo ""
	        scriptname=`basename $0`
	        echo "  usage: $scriptname [-m] [url]" >&2
	        echo "  -m will open mail client with tinyurl" >&2
		echo "  if url not present on command line, will copy from clipboard" >&2
		echo ""
		echo "  author: jake hofman <gmail: jhofman>" >&2
		echo ""
		exit 1;
		;;
  esac
done


shift $((OPTIND - 1))

# if we have a url left on the command line, grab it. otherwise paste from clipboard
if [ $# -lt 1 ]
    then
    orig=`pbpaste`
else
    orig=$1
 fi

# grab tinyurl that was created
# jntj: changed on 2008.10.16 to use tinyurl api
# new hotness:
tiny=`lynx -source "http://tinyurl.com/api-create.php?url=$orig"`
# old and busted:
# tiny=`lynx -source "http://tinyurl.com/create.php?url=$orig" |
#	grep "type=hidden name=tinyurl value=" |
#       cut -d \" -f 2 `

echo tiny: $tiny
echo original: $orig

# grab title of page (better way to do this than in perl?)
title=`lynx -source $orig | perl -e ' $flat = join("",<STDIN>); $flat =~ /\<title\>(.*?)\<\/title\>/i; print $1; '`
#title=`htmltag title "$orig"`

# copy tinyurl to clipboard
if [ "$copytitle" = 1 ]
    then
    echo -n "$title: $tiny" | pbcopy
else
    echo -n $tiny | pbcopy
fi

# if we haven't already created this tinyurl, add to file
if ! grep "$tiny" $tinyfile > /dev/null
then
    echo `date +%m.%d.%y%t%R%t` "$tiny $orig \"$title\"" >> ~/tinyurls.txt
fi

# if -m option passed, mail link
if [ $mailtiny = 1 ]
    then
    subj=`echo "$title" | sed -e 's/ /\%20/g'`
    # convert & in original url to %26
    orig=${orig//&/%26}
    #orig=`echo "$orig" | urlencode`
    open "mailto:$address?subject=$subj&body=%0D%0D%20%20$tiny%0A%20%20(original%20link:%20$orig%20)"
    # copy original link back to clipboard (switch to disable this?)
    echo "$orig" | pbcopy
fi