#!/usr/bin/env ruby
require 'net/http'

HOST = "i.ralph.io"
common_images_extensions = [".png", ".jpg", ".jpeg", ".gif"]

# capture file
tmpfile = "/tmp/upload"
filepath = ARGV[1]
existing_file = filepath && File.exist?(filepath)

if existing_file then
  tmpfile = filepath
else
  tmpfile << ".png"
  system "screencapture -i \"#{tmpfile}\""
  if File.exist?(tmpfile) then
    system "sips -d profile --deleteColorManagementProperties \"#{tmpfile}\""  
  end
end

ext = File.extname(tmpfile).downcase
is_image = common_images_extensions.include?(ext)

exit unless File.exist?(tmpfile)
filedata = File.read(tmpfile)

# upload
boundary = '----LOLOLOLOLObuttsLOLOLOLOL----'

data = <<EOF
--#{boundary}\r
content-disposition: form-data; name="filedata"; filename="#{tmpfile}"\r
\r
#{filedata}\r
--#{boundary}--\r
EOF

header = {
  'Content-Length' => data.length.to_s,
  'Content-Type' => "multipart/form-data; boundary=#{boundary}",
  'User-Agent' => "ralphholzmann's screen grabs"
}

Net::HTTP.start(HOST,80) { |http|
  res = http.post("/", data, header)
  url = res.response.body
  IO.popen("pbcopy", "r+") { |io|
    io.write url
    io.close
  }

  if is_image
    system "terminal-notifier -message '#{url}' -title 'Image uploaded successfully.' -contentImage #{tmpfile}"
  else
    system "terminal-notifier -message '#{url}' -title 'File uploaded successfully.'"
  end

  File.delete(tmpfile) unless existing_file
}