#!/usr/bin/env ruby

$books_path = '/home/dave/wiki/ratf/src/b'

if ARGV.count < 1
  puts "ERROR: You gotta send me a line of text!"
  exit 1
end

bookline = ARGV[0]

date, title, author, pages = nil

# Now the input, bookline, is one of two things:
# * A journal entry
# * A website link
if bookline.match?(/^[0-9-]+  /)
  bits = bookline.rstrip.split(/\s{2,}/)
  if bits.size != 4
    puts "ERROR: Line didn't match expected book journal format:"
    puts bookline
    exit 1
  end
  date, title, author, pages = bits

  # =======================================================
  # Journal entry, create website link

  index_page = "#{$books_path}/index.adoc"
  index_page_temp = "#{$books_path}/index.adoc.temp"
  fname = title.downcase.gsub(/ +/, '_').gsub(/[^a-z0-9_-]+/, '')

  # Read lines of existing books page, collect
  my_lines = []
  File.foreach(index_page) do |line|
    my_lines << line

    # insert new link in books page
    if line.match(/ENTRIES_HERE/)
      my_lines << "* #{date} link:#{fname}[#{title}] by #{author}, #{pages} pages"
    end
  end

  # Write new books page with link added
  File.open(index_page_temp, 'w') do |f|
    f.puts my_lines # writes all lines
  end

  # if the OLD page is bigger than the new one, do NOT continue!
  if File.size(index_page) > File.size(index_page_temp)
    puts "ERROR: Books page is smaller after writing link...so something went wrong!"
    puts "Check it at: #{index_page_temp}"
    puts "Exiting and not doing anything else."
    exit 1
  end

  # the NEW page is bigger than the old, so replacing old with new
  File.unlink(index_page)
  File.rename(index_page_temp, index_page)

  # now write the filename out so vim can open it
  puts index_page

elsif bits = bookline.match(/^\* ([0-9-]+) link:(.*)\[(.*)\] by (.*), (\d+) pages/)

  # =======================================================
  # Books page link. Create review page.

  _, date, fname, title, author, pages = bits.to_a
  fname = "#{$books_path}/#{fname}.adoc"

  if File.exist?(fname)
    puts "ERROR: #{fname} already exists."
    exit 1
  end

  # Write new books page with link added
  File.open(fname, 'w') do |f|
    f.puts <<~HTML
      :title: Dave's book review for #{title}
      :created: #{Time.new.strftime('%Y-%m-%d')}
      :updated:

      ++++
      <div style="background-color: #EFC;">
      Book: <b>#{title}</b><br>
      Author: <b>#{author}</b><br>
      Pages: <b>#{pages}</b><br>
      Finished reading: <b>#{date}</b><br>
      Back to <a href=".">my books page</a> for more reviews, etc.
      </div>
      ++++

      == My Review
    HTML
  end

  # Return file name so vim can open it
  puts fname

  exit
else
  puts "ERROR: Input param does not look like journal entry or web link!"
  exit 1
end
