#!/usr/bin/env ruby

# Add the path to your config file here
CONFIG_FILES = [
  "/path/to/your/wordpress/wp-content/plugins/feedcache/feedcache-config1.txt",
  "/path/to/your/wordpress/wp-content/plugins/feedcache/feedcache-config2.txt",
  "/path/to/your/wordpress/wp-content/plugins/feedcache/feedcache-config3.txt",
  "/path/to/your/wordpress/wp-content/plugins/feedcache/feedcache-config4.txt"
  ]
# add your cache file paths here
CACHE_FILES = [
  "/path/to/your/wordpress/wp-content/plugins/feedcache/feedcache-cache1.txt",
  "/path/to/your/wordpress/wp-content/plugins/feedcache/feedcache-cache2.txt",
  "/path/to/your/wordpress/wp-content/plugins/feedcache/feedcache-cache3.txt",
  "/path/to/your/wordpress/wp-content/plugins/feedcache/feedcache-cache4.txt"
  ]
# How many characters from each feed item do you want to display
CHAR_COUNT = 75
# Set to 'true' if you want to receive error emails from the CRON job
CRON_EMAILS = false


#################################
#                               #
#  DO NOT EDIT BELOW THIS LINE  #
#                               #
#################################
require 'net/http'
require 'rss/2.0'
require 'open-uri'
require 'yaml'
require 'tempfile'

# RSS formatting function
def shorten_text(txt)
  @text = txt + ' '
  @text = @text.slice(0,CHAR_COUNT)
  # need to break on the last space
  # @text = 
  @text = @text + '...' if @text.size > CHAR_COUNT
  return @text
end

begin # read the config file settings
  @all_feeds = {}
  CONFIG_FILES.each_with_index do |cfg_file, idx|
    config = File.open(cfg_file, 'r') do |f|
      @feeds = []
      @params = f.gets.split('~')
      while line = f.gets
        @feeds << line.strip
      end
    end
    @all_feeds[idx] = @feeds
  end
rescue => e
  if CRON_EMAILS
    puts "Error reading configuration file"
    puts YAML.dump(e)
  end
end  

# parse the parameters from the config file
@display_num, @title_pre, @title_post, @format_text = @params[0].strip, @params[1].strip, @params[2].strip, @params[3].strip

@all_feeds.each do |k,v|
  @tmp = Tempfile.new("feedcache#{k}")
  @processed = 0

  # parse the feeds here
  v.each do |feed|
    #puts "\nFEED -> #{feed}\n"
    @html_text = ''
    data = feed.split('|')
    feed_url, feed_title, feed_num, feed_format = data[0], data[1], data[2], data[3]
    begin
      open(feed_url, "User-Agent" => "dfRssCrawler/1.0 (compatible; http://www.developerfusion.com/blogs/)") do |http|
        response = http.read
        result = RSS::Parser.parse(response, false)
        next if result.nil?
        @html_text << @title_pre + (feed_title || result.channel.title) + @title_post
        @html_text << "<ul>"
        result.items.each_with_index do |item, idx|
          break if feed_num ? feed_num.to_i == idx.to_i : @display_num.to_i == idx.to_i
          output = ''
          output << "<li><a href='#{item.link}'>"
          if feed_format && feed_format == 'true'
            txt = "#{item.title.downcase.gsub(/^[a-z]|\s+[a-z]/) {|a| a.upcase}}"
            output << shorten_text(txt)
          elsif @format_text == 'true'
            txt = "#{item.title.downcase.gsub(/^[a-z]|\s+[a-z]/) {|a| a.upcase}}"
            output << shorten_text(txt)
          else
            output << "#{item.title}"
          end
          output << "</a></li>\n"
          @html_text << output
        end
        @html_text << "</ul><br />\n"
        @tmp << @html_text
        @processed += 1
      end
    rescue OpenURI::HTTPError => e
      #puts "Error processing feed - #{feed_url}"
      #puts e.message
    rescue => e
      puts "Error processing feed - #{feed_url}"
      puts YAML.dump(e)
    end  
  end

  @tmp.close
  # if we had new feeds, move them to the cache file
  if @processed > 0
    @tmp.open
    @cache = File::open(CACHE_FILES[k], "w")
    @cache << @tmp.gets(nil)
    @cache.close
    @tmp.close(true) # remove the /tmp file
  end
end #--> @all_feeds.each do |k,v|