#!/usr/bin/env ruby                                  

=begin

 inspired by defunkt's gist ( http://github.com/defunkt/gist )

USE:

  pickhost <filename>

=end

require 'pathname'
require 'yaml'
require 'json'
require 'httpclient'

module Pickhost
  extend self

  def parse(input)
    return help if input == '-h' || input.nil? || input[/help/]
    upload(Pathname(input).realpath)
  end

  def upload(file)
    url = URI.parse('http://pickhost.eu/api/upload')
    response = JSON.parse(
      HTTPClient.post(url, { :client_key => "54c56f1de2678ac4d32aa19fb66fe06c",
                             :file => File.new(file) }.merge(auth)).body.content )
    return response["errors"] if response["errors"]
    copy response["image"]["public_view_url"]
  end

  def help
    "USE:\n  " + File.read(__FILE__).match(/USE:(.+?)=end/m)[1].strip
  end

private
  # stolen from defunkt's gist ( http://github.com/defunkt/gist )
  def copy(content)
    case RUBY_PLATFORM
    when /darwin/
      return content if `which pbcopy`.strip == ''
      IO.popen('pbcopy', 'r+') { |clip| clip.puts content }
    when /linux/
      return content if `which xclip 2> /dev/null`.strip == ''
      IO.popen('xclip', 'r+') { |clip| clip.puts content }
    end

    content
  end

  def auth
    path = File.expand_path("~#{ENV['USER']}/.pickhost-cli.yml")
    hsh = File.exist?(path) ? YAML.load_file(path) : {}

    hsh
  end
end

puts Pickhost.parse(ARGV.first)
