#!/usr/bin/env ruby

require "bundler/setup"
require "licensed/cli"
require "optparse"

module Licensed
  module Source
    class Filesystem

      def self.type
        "grammar"
      end

      def initialize(glob)
        @glob = glob
      end

      def enabled?
        !Dir.glob(@glob).empty?
      end

      def submodule_version(directory)
        return unless directory
        Dir.chdir directory do
          Licensed::Git.version(".")
        end
      end

      def dependencies
        Dir.glob(@glob).map do |directory|
          Licensed::Dependency.new(directory, {
            "type" => Filesystem.type,
            "name" => File.basename(directory),
            "version" => submodule_version(directory)
          })
        end
      end
    end
  end
end

module_path = nil
OptionParser.new do |opts|
  opts.on("-mPATH", "--module=PATH", "Cache license file for specific grammar") do |p|
    module_path = p
  end
end.parse!

source = Licensed::Source::Filesystem.new(module_path || "#{File.expand_path("../", File.dirname(__FILE__))}/vendor/grammars/*/")
config = Licensed::Configuration.load_from(File.expand_path("../vendor/licenses/config.yml", File.dirname(__FILE__)))
config.sources << source

command = if ARGV[0] == "status"
  Licensed::Command::Status.new(config)
else
  Licensed::Command::Cache.new(config)
end

command.run
`git checkout -- vendor/licenses/grammar/` if module_path
exit command.success?
