#!/usr/bin/env nix-shell
#!nix-shell --packages linuxHeaders ruby -i ruby

# This script can be used to update the input_event_codes ruby file.
# The file is intended to be committed and updated as needed.
# At worst, an outdated file will lack *newly introduced* identifiers.
# This is not much of an issue when most of the kernels for this
# project are of older vintage!
# On the same idea, using newer headers is never an issue with "kernel
# header files". In this particular instance, at worst you're looking
# for an identifier the kernel does not know about, so it will never
# return it.

HEADERS = ENV["buildInputs"].split(/\s+/).grep(/linux-headers/).first
INPUT_CODES = File.join(HEADERS, "/include/linux/input-event-codes.h")

parsed = File.read(INPUT_CODES).lines.grep(/^#define/).map do |line|
  line.split("/*").first.sub(/^#define/, "").strip.split(/\s+/, 2)
end.reject { |pair| pair.first.match(/^_/) }

mod = <<~EOF
# This is generated by `generate_evdev_data.rb`.
# If an update is needed, simply run the script.
module Linux
  module InputEventCodes
#{
  parsed.map do |pair|
    name, value = pair
    %Q{    #{name} = #{value}}
  end.join("\n")
}
  end
end
EOF

# Verify it works
eval mod

# A bit of additional checks
{
  EV_KEY: 1,
  KEY_Q: 16,
  KEY_VOLUMEUP: 115,
}.each do |k, v|
  actual = Linux::InputEventCodes.const_get(k)
  unless actual == v
    raise "The module probably is not right. #{k} != #{v} // #{k} = #{actual}"
  end
end

path = File.join(__dir__(), "..", "lib/linux/input_event_codes.rb")
File.write(path, mod)
puts "Wrote '#{path}'."
