#!/usr/bin/env ruby
# -*-mode: ruby; coding: utf-8;-*-
# (C) Thomas Hafner 2011
# gopher://sdf-eu.org/1/users/hafner/devel/tinyurl/

$-K='U'

require 'cgi'
require 'mechanize'

module Tinyurl
 def self.encode(original_url)
   raise 'No original URL given.' unless original_url
   Mechanize.new.
     get("http://tinyurl.com/create.php?url=#{CGI::escape(original_url)}").
     link_with(:text => 'Open in new window').
     href
 end

 def self.decode(tiny_url)
   raise 'No tiny URL given.' unless tiny_url
   url = tiny_url.sub(%r{^http://tinyurl.com/}i, 'http://preview.tinyurl.com/')
   Mechanize.new.
     get(url).
     link_with(:text => 'Proceed to this site.').
     href
 end
end

if __FILE__ == $0
 require 'getoptlong'

 options = \
 [ [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
   [ '--decode', '-d', GetoptLong::NO_ARGUMENT ],
 ]

 OPTS = Hash[*GetoptLong.new(*options).to_enum.to_a.flatten]

 if OPTS.has_key?('--help')
   b = File::basename($0)
   puts <<"EOS"
Usage:
#{b} ORIGINAL_URL
#{b} --decode TINY_URL
EOS
 else
   url, = ARGV
   method = OPTS.has_key?('--decode') ? :decode : :encode
   puts Tinyurl.send(method, url)
 end
end