#!/usr/bin/env ruby

# Add the path to your feedcache directory here
FCPIPES_DIR = '/path/to/your/feedcache-pipes/plugin/directory'
# 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                                  #
#                                                               #
#################################################################
$LOAD_PATH << File.expand_path(File.dirname(__FILE__))

require 'net/http'
require 'lib/feedparser'
require 'uri'
require 'yaml'
require 'tempfile'

# Read master config settings
MASTER_CONFIG = "#{FCPIPES_DIR}/master-config.txt"
cfg = File.open(MASTER_CONFIG, 'r') do |f|
  @params = f.gets.split('~');
end

# parse the parameters from the config file
@groups_num   = @params[0].strip.to_i
@display_num  = @params[1].strip
@format_text  = @params[2].strip == 'true' ? true : false
@link_target  = @params[3].strip == 'true' ? '_blank' : '_self'

# Load config and cache file variables
CONFIG_FILES, CACHE_FILES = [], []
1.upto(@groups_num) do |i|
  CONFIG_FILES << "#{FCPIPES_DIR}/files/fcpipes-config#{i}.txt"
  CACHE_FILES << "#{FCPIPES_DIR}/files/fcpipes-cache#{i}.txt"
end

# RSS formatting function
def shorten_text(txt)
  if txt.size > CHAR_COUNT
    @text = "#{txt} ".slice(0,CHAR_COUNT)
    # need to break on the last space
    if @text.include?(' ') and @text.slice(@text.size-1, 1) != ' '
      @text.slice!(0, @text.size - (@text.reverse.index(' ') + 1))
      @text << '...'
    end
    return @text
  else
    return txt
  end
end

begin # read the config files settings
  @all_feeds = Hash.new
  CONFIG_FILES.each_with_index do |cfg_file, idx|
    config = File.open(cfg_file, 'r') do |f|
      @feeds = Array.new
      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  

@entry_groups = Hash.new

# process the feed list
@all_feeds.each do |k, v|
  @entries = Hash.new
  # parse the feeds
  v.each do |feed|
    begin
      source = Net::HTTP::get URI::parse(feed)
      fp = FeedParser::Feed::new(source)
      fp.items.each do |item|
        @entries[item.date.to_i] = item
      end
    rescue => e
      if CRON_EMAILS
        puts "Error processing feed - #{feed}"
        puts YAML.dump(e)
      end
    end
  end
  @entry_groups[k] = @entries
end #--> @all_feeds.each do |k,v|
  
# now process each group by timestamp
@entry_groups.each do |k,v|
  @tmp = Tempfile.new("fcpipes#{k}")
  @processed = false
  @count = 1
  @html_text = "<ul class='fcpipes'>"
  
  # sort entries by timestamp and process
  v.sort {|a,b| b[0]<=>a[0]}.each do |key, item|
    break if @count > @display_num.to_i
    output = ''
    output << "<li><a href='#{item.link}' target='#{@link_target}'>"
    if @format_text
      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
    @count += 1
  end
  
  @html_text << "</ul><br />\n"
  @tmp << @html_text
  @processed = true

  @tmp.close

  # if we had new feeds, move them to the cache file
  if @processed
    @tmp.open
    @cache = File::open(CACHE_FILES[k], "w")
    @cache << @tmp.gets(nil)
    @cache.close
    @tmp.close(true) # remove the /tmp file
  end
end # end @entry_groups.each do |k,v|
