#!/usr/bin/env ruby

require_relative "../../version_policy"

old_version, new_version = ARGV[0..1]

require "set"
ENV["BUNDLE_WITHOUT"] = INSTALL_WITHOUT_GROUPS.join(":")
relevant_gems = Set.new
`bundle list`.each_line do |line|
  next unless line =~ /^  \* (\S+)/
  relevant_gems.add($1)
end

old_gems = {}
old_file = `git show #{old_version}:Gemfile.lock`
old_file.each_line do |line|
  next unless line =~ /^    (\S+) \(([^\)]+)\)$/
  next unless relevant_gems.include?($1)
  old_gems[$1] = $2
end

new_gems = {}
new_file = `git show #{new_version}:Gemfile.lock`
new_file.each_line do |line|
  next unless line =~ /^    (\S+) \(([^\)]+)\)$/
  next unless relevant_gems.include?($1)
  new_gems[$1] = $2
end

modified_gems = (old_gems.keys & new_gems.keys).sort.select { |name| new_gems[name] != old_gems[name] }.map { |name| "#{name} - #{new_gems[name]} (was #{old_gems[name]})" }
removed_gems = (old_gems.keys - new_gems.keys).sort.map { |name| "#{name} - #{old_gems[name]}" }
added_gems = (new_gems.keys - old_gems.keys).sort.map { |name| "#{name} - #{new_gems[name]}" }

puts "MODIFIED:\n#{modified_gems.join("\n")}" if modified_gems.any?
puts "\nADDED:\n#{added_gems.join("\n")}" if added_gems.any?
puts "\nREMOVED:\n#{removed_gems.join("\n")}" if removed_gems.any?
