#!/usr/bin/env ruby
# frozen_string_literal: true

require 'optparse'
require 'action'

OptionParser.new do |parser|
  parser.version = File.read("#{__dir__}/../VERSION")
  parser.banner += ' workflows ...'
  parser.on('-n', '--newer', 'deal only with actions that have an update') do
    @newer = true
  end
  parser.on('-w', '--write', 'write updates back to workflow files') do
    @write = true
  end
end.parse!

ARGV.each do |path|
  puts "==> #{path}"
  yaml = File.read(path)
  actions = Action.array_from_yaml(yaml)
  actions.each do |current_action|
    new_action = current_action.clone
    new_action.ref = current_action.latest_tag

    next if current_action == new_action && @newer

    puts "#{current_action} -> #{new_action}"

    next unless @write

    yaml.gsub!(/#{current_action}/, new_action.to_s)
    File.open(path, 'w') { |f| f.puts yaml }
  end
end