# Attributes

BASE = %w(
  attach:string
  title:string
  author:string
  shepard:string
)

MORE = %w(
  approved:string
  text:text
  comments:text
)

EDIT = %w(
  notes:text
)

# establish project
if ARGV.first == 'clean'
  require 'fileutils'
  FileUtils.rm_rf 'agenda'
  ARGV.shift
end

# create project for this months board report
if File.exist? 'agenda'
  Dir.chdir 'agenda'
else
  system 'rails agenda'
  Dir.chdir 'agenda'

  system "ruby script/generate scaffold report #{BASE.join(' ')}"
  system "ruby script/generate migration AddMoreToReport #{MORE.join(' ')}"
  system "ruby script/generate migration AddEditToReport #{EDIT.join(' ')}"
  system 'rake db:migrate'

  # helper for editing files
  def edit(filepath)
    data = File.open(filepath) {|file| file.read} rescue ''
    yield data
    File.open(filepath,'w') {|file| file.write data}
  end

  # primary index
  edit('app/views/reports/index.html.erb') do |data|
    # make the h1 useful
    data[/<h1>(.*?)<\/h1>/,1] = 
      File.basename(ARGV.first).split('.').first.gsub('_',' ')

    # style rows containing data
    data[/<tr()>\s+<td>/,1] = ' <%= "class=#{status(report)}" %>'

    # delete extra links
    data.gsub! /.* link_to '.*\n/, ''

    # make title hypertext
    data[/=(h report.title)/,1] = 
      ' link_to report.title, edit_report_path(report)'
  end

  # report helper
  edit('app/helpers/reports_helper.rb') do |data|
    data[/^()end/,1] = <<-'EOF'.gsub(/^    /,'')
      def status(report)
        if report.text.to_s.blank?
          'missing'
        elsif report.approved.to_s.split(/(?:,\s*|\s+)/).size < 6
          'ready'
        elsif report.comments.to_s.size > 0
          'commented'
        else
          'reviewed'
        end
      end
    EOF
  end

  # create a stylesheet
  edit('public/stylesheets/reports.css') do |data|
    data << <<-EOF.gsub(/^      /,'')
      /* row colors */
      .missing   {background-color: #F55}
      .ready     {background-color: #FA0}
      .reviewed  {background-color: #9F9}
      .commented {background-color: #FF0}

      /* make the header an eye catcher */
      h1 {
        line-height: 2em;
        text-align: center;
        text-transform: capitalize
      }

      /* center the table */
      table {
        margin-left: auto;
        margin-right: auto
      }

      /* table borders */
      table, td, th {
        border-color: #600;
        border-style: solid;
        border-width: 1px;
      }

      table {
        border-spacing: 0;
        border-collapse: collapse;
      }

      td, th {
        margin: 0;
        padding: 4px;
      }

      tr {
        background-color: #FFC;
      }

      tr.new {
        background-color: yellow
      }
    EOF
  end

  # link the stylesheet
  edit('app/views/layouts/reports.html.erb') do |data|
    data[/stylesheet_link_tag.*() %>/,1] = ", 'reports'"
  end

  # edit report
  edit('app/views/reports/edit.html.erb') do |data|
    # make the h1 useful
    data[/(<h1>.*?<\/h1>)/,1] = 
      '<h1 class="<%= status(@report) %>"><%=h @report.title %></h1>'

    # zap title
    data[/<p>(\s*<b>Title<\/b>.*?<p>)/m,1] = ''

    # make BASE fields readonly
    data.gsub! /f.text_field (\S+)/, 'f.text_field \1, :readonly => true'

    # replace 'show' with 'next'
    data[/link_to ('Show', .*) %>/,1] = 
      "'Next', edit_report_path(@report.id + 1)"

    # add MORE fields
    data[/\n()\s+<p>\s+<%= f.submit/,1] = (
      MORE.map do |field| 
        name,type = field.split(':')
        <<-EOF.gsub(/^        /,'')
          <p>
            <b>#{name.capitalize}</b><br />
            <pre><%=h @report.#{name} %></pre>
          </p>
        EOF
      end.join("\n") + "\n"
    )

    # add EDIT fields
    data[/\n()\s+<p>\s+<%= f.submit/,1] = (
      EDIT.map do |field| 
        name,type = field.split(':')
        <<-EOF.gsub(/^        /,'')
          <p>
            <b>#{name.capitalize}</b><br />
            <%= f.text_area :#{name}, :cols => 80 %>
          </p>
        EOF
      end.join("\n") + "\n"
    )
  end

  # change update from redirecting to 'show' to redirect to 'next'
  edit('app/controllers/reports_controller.rb') do |data|
    data.gsub! 'redirect_to(@report)',
      'redirect_to(edit_report_url(@report.id+1))'
  end

  # disable session support
  edit('app/controllers/application.rb') do |data|
    data[/()^end/,1] = "\n  self.allow_forgery_protection=false\n"
    data[/()^end/,1] = "\n  session :disabled => true\n"
  end
end

require 'rubygems'
require 'config/environment.rb'

agenda = open(ARGV.first).read

# Executive Officer Reports
agenda.split(/^ 4. Executive Officer Reports/,2).last.
       split(/^ 5. Additional Officer Reports/,2).first.scan(/
  \s{4}([A-Z])\.          # section
  \s([^\[]+?)             # title
  \s\[([^\]]+?)\]         # owner
  (.*?)                   # text
  (?=\n\s{4}[A-Z]\.\s|\z) # next section
/mx).each do |section,title,owner,text|
  attach = '4' + section
  report = Report.find_by_attach(attach) || Report.new
  report.attach = attach
  report.author = report.shepard = owner
  report.title = title
  report.text = text
  report.save!
  puts title
end

# Additional Officer Reports and Committee Reports (part I)
agenda.scan(/
  -{41}\n                     # separator
  Attachment\s(\w+):\s(.*?)\n # Attachment, Title
  .(.*?)\n                    # report
  (?=-{41})                   # separator
/mx).each do |attach,title,text|
  title.sub! /^Report from the VP of /, ''
  title.sub! /^Status report for the /, ''
  title.sub! /^Apache /, ''
  title.sub! /\sTeam$/, ''
  title.sub! /\sCommittee$/, ''
  title.sub! /\sProject$/, ''

  report = Report.find_by_attach(attach) || Report.new
  report.attach = attach
  report.title = title
  report.text  = text
  report.save!
  puts title
end

# Additional Officer Reports and Committee Reports (part II)
agenda.scan(/
  \[([^\n]+)\]\n\n                 # owners
  \s{7}See\sAttachment\s(\w+)\s+   # attach
  \[\sapproved:\s*?(.*?)           # approved
  \s*comments:(.*?)\n\s{9}\]       # comments
/mx).each do |owners,attach,approved,comments|
  report = Report.find_by_attach(attach) || Report.new

  if owners.include? '/'
    report.author, report.shepard = owners.gsub(%r{\s*/\s*} ,'/').split('/',2)
  else
    report.author = report.shepard = owners
  end

  report.attach = attach
  report.approved = approved.gsub(/\s+/,' ').strip
  report.comments = comments.gsub(/^         /,'')
  report.save!
end

# Special Orders
agenda.split(/^ 7. Special Orders/,2).last.
       split(/^ 8. Discussion Items/,2).first.scan(/
  \s{4}([A-Z])\.          # section
  \s(.*?)\n               # title
  (.*?)                   # text
  (?=\n\s{4}[A-Z]\.\s|\z) # next section
/mx).each do |section,title,text|
  attach = '7' + section
  report = Report.find_by_attach(attach) || Report.new
  report.attach = attach
  report.text = "#{title}\n#{text}"

  title.sub! /\sthe\s/, ' '
  title.sub! /\sApache\s/, ' '
  title.sub! /\sCommittee\s/, ' '
  title.sub! /\sProject\s/, ' '

  report.title = title
  report.save!
  puts title
end

system 'ruby script/server'
