#!/usr/bin/env ruby -rjcode -Ku

$KCODE = 'u'
UNICODE_COMPETENT = ((RUBY_VERSION)[0..2].to_f > 1.8)

unless UNICODE_COMPETENT # lower than 1.9
  class String
     def utf8_length
        i = 0
        i = self.scan(/(.)/).length
        i
     end
  end
else # 1.9 and above
  class String
     alias_method :utf8_length, :length
  end
end

def entity_escape(text)
  text.gsub(/&(?!([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);)/, '&amp;')
end

def make_link(text)
  case text
  when %r{\A(mailto:)?(.*?@.*\..*)\z}:
     "mailto:#{$2}"
  when %r{http://www.(amazon.(?:com|co.uk|co.jp|ca|fr|de))/.+?/([A-Z0-9]{10})/[-a-zA-Z0-9_./%?=&]+}:
     "http://#{$1}/dp/#{$2}"
  when %r{\A[a-zA-Z][a-zA-Z0-9.+-]*://.*\z}:
     entity_escape(text)
  when %r{\A(www\..*|.*\.(com|uk|net|org|info))\z}:
     "http://#{entity_escape text}"
  when %r{\A.*\.(com|uk|net|org|info)\z}:
     "http://#{entity_escape text}"
  else
     false
  end
end

input = STDIN.gets nil
pboard = %x{__CF_USER_TEXT_ENCODING=$UID:0x8000100:0x8000100 pbpaste}.strip
link = make_link(pboard)

if link
  print "[#{input}](#{link})"
else
  print "[#{input}]()"
end