Initial checkin
[grml-paste.git] / grml-paste
1 #!/usr/bin/env ruby
2 # Filename:      grml-paste
3 # Purpose:       paste files to the online grml paste bot
4 # Authors:       grml-team (grml.org), (c) 2007 Nico Golde <nico@grml.org>
5 # Bug-Reports:   see http://grml.org/bugs/
6 # License:       This file is licensed under the GPL v2
7 ##########################################################################
8
9 require 'uri'
10 require 'net/http'
11
12 url = URI.parse('http://paste.grml.org/paste')
13
14 def usage
15         $stderr.puts "usage: #{$0} [-n nick] [-s summary] [-f source] [-h|--help]\n"
16         $stderr.puts "\t -n <nick>\tset your nickname (defaults to Anonymuos)"
17         $stderr.puts "\t -s <summary>\tspecify a summary of your paste (defaults to none)"
18         $stderr.puts "\t -f <source>\tsets the file to read from, you don't need this for reading from stdin"
19         $stderr.puts "\t --help\t\tprint this help"
20         Kernel.exit(1)
21 end
22
23 file    = nil
24 summary = "none"
25 nick    = "Anonymous"
26 channel = "#grml"
27 text    = ""
28
29 ARGV.each_index do |i|
30         if ARGV[i] == '-h' or ARGV[i] == '--help' then
31                 usage
32         elsif ARGV[i] == '-n' and ARGV[i+1] != nil then
33                 nick = ARGV[i+1]
34         elsif ARGV[i] == '-s' and ARGV[i+1] != nil then
35                 summary = ARGV[i+1]
36         elsif ARGV[i] == '-f' and ARGV[i+1] != nil then
37                 file = ARGV[i+1]
38         end
39 end
40
41 if file == nil or file == "-"
42         f = STDIN
43 else
44         begin
45                 f = File.open(file)
46         rescue
47                 $stderr.puts "Error: couldn't open file: #{file}"
48                 Kernel.exit(1)
49         end
50 end
51
52 f.each_line do |line|
53         text << line
54 end
55
56 begin
57         res = Net::HTTP.post_form(url,{'Paste it' => 'Paste it', 'paste' => text, 'channel' => channel,  'summary' => summary, 'nick' => nick})
58 rescue
59         $stderr.puts "Unable to post HTTP request"
60         Kernel.exit(1)
61 end
62
63 results = res.body.scan(/<a href='http:\/\/paste.grml.org\/[0-9]+'/)
64 result = ""
65 if results.size > 0 then
66         result = results[0].sub(/<a href='(http:\/\/paste.grml.org\/[0-9]+)'/, '\1')
67 end
68
69 if result == "" then
70         print "Failed to paste, please retry\n"
71 else
72         print "You can find your paste on: " + result + "\n"
73 end
74
75 ## END OF FILE #################################################################