#!/usr/bin/env ruby

require "json"
require "rss"
require "open-uri"
require "typhoeus"

debug = ARGV[0] == "debug"
ARGV.shift if debug

user = ARGV[0]
token = ARGV[1]
proxy = ARGV[2]

lm = Time.now.to_s
nots = {}

options = { proxy: proxy, userpwd: "#{user}:#{token}" }
hydra = Typhoeus::Hydra.new(max_concurrency: 20)

putc ">" if debug
res = JSON.parse(Typhoeus.get("https://api.github.com/notifications", options).body)
puts "<" if debug

res.each do |n|
    nots.store n["id"], {
        title: "#{n["repository"]["full_name"]}: #{n["subject"]["title"]}",
        updated: n["updated_at"]
    }
    request = Typhoeus::Request.new(n["subject"]["latest_comment_url"] || n["subject"]["url"], options)
    putc ">" if debug
    request.on_complete do |response|
        putc"<" if debug
        nots[n["id"]][:link] = JSON.parse(response.body)["html_url"]
    end
    hydra.queue(request)
end

puts if debug

hydra.run

feed = RSS::Maker.make("2.0") do |maker|

    maker.channel.title = "GitHub Notifications"
    maker.channel.id = "htto://github.com/notifications/#{user}"
    maker.channel.author = "GitHub"
    maker.channel.link = "http://github.com/notifications"
    maker.channel.description = "GitHub Notifications"
    maker.channel.updated = lm

    nots.each do |id, n|
        maker.items.new_item do |item|
            item.title = n[:title]
            item.guid.content = "https://github.com/notifications/notification/#{id}"
            item.guid.permanent_link = false
            item.updated = n[:updated]
            item.link = n[:link]
        end
    end
end

puts feed unless debug