#!/usr/bin/env ruby

# Add the path to your config file here
CONFIG_FILE = "/path/to/your/wordpress/wp-content/plugins/feedcache/feedcache-config.txt"
# Add the path to your cache file here
CACHE_FILE = "/path/to/your/wordpress/wp-content/plugins/feedcache/feedcache-cache.txt"
# How many characters from each feed item do you want to display
CHAR_COUNT = 75


#################################
#                               #
#  DO NOT EDIT BELOW THIS LINE  #
#                               #
#################################
require 'net/http'
require 'rss/2.0'
require 'open-uri'
require 'yaml'

# 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
  config = File.open(CONFIG_FILE, 'r') do |f|
    @feeds = []
    @params = f.gets.split('~')
    while line = f.gets
      @feeds << line.strip
    end
  end
rescue => e
  puts "Error reading configuration file"
  puts YAML.dump(e)
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

@cache = File::open(CACHE_FILE, "w")

# parse the feeds here
@feeds.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) 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'
          output << "#{item.title.downcase.gsub(/^[a-z]|\s+[a-z]/) {|a| a.upcase}}"
        elsif @format_text == 'true'
          output << "#{item.title.downcase.gsub(/^[a-z]|\s+[a-z]/) {|a| a.upcase}}"
        else
          output << "#{item.title}"
        end
        output << "</a></li>\n"
        @html_text << output
      end
      @html_text << "</ul><br />\n"
      @cache << @html_text
    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

@cache.close