#!/usr/bin/env ruby
#
# Copyright (c) 2013 ModCloth, Inc.
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


require 'json'

def main(argv = ARGV.freeze)
  if ARGV.include?('-h') || ARGV.include?('--help')
    $stdout.puts "Usage: #{File.basename($0)} <node-module-dir>"
    return 0
  end

  update_index(ARGV.fetch(0))
  return 0
end

def update_index(mod)
  index = {}
  index_file = File.join(mod, '.index.json')

  if File.exists?(index_file)
    begin
      JSON.parse(File.read(index_file)).each do |k,v|
        if k.to_s == k && v.to_s == v
          index[k] = v
        end
      end
    rescue => e
      $stderr.puts "#{e.class.name} #{e.message}"
      if ENV['DEBUG']
        $stderr.puts e.backtrace.join("\n")
      end
    end
  end

  File.open("#{mod}/.index.json", 'w') do |f|
    f.puts JSON.pretty_generate(generate_module_index(mod, index))
  end
end

def generate_module_index(mod, index = {})
  Dir.glob("#{mod}/*.*").each do |script|
    if File.file?(script) && File.executable?(script)
      key = File.basename(script)
      index[key] = script_description(script, index[key])
    end
  end

  index
end

def script_description(script, default = '')
  if %w(.elf .bin).include?(File.extname(script))
    default || ''
  else
    (File.read(script).split($/).grep(/Description:/).first || default || '').
      sub(/.*Description:/, '').strip
  end
end

if $0 == __FILE__
  exit main(ARGV)
end
