#!/usr/bin/env ruby

def run(name)
  `#{File.join(__dir__, name)}`
end

def stat(key, val = '')
  puts "#{key} #{val}"
end

# Run the fs changes hook, so that /etc/hosts is created on startup
# but don't print the results
run 'ctld-changed'

# Run the ctld-runtime hook and print the results
puts run 'ctld-runtime'

vendor = ''
dmi = `sudo dmidecode`.split("\n\n").each do |section|
  if section.include?("Processor Information")
    section.lines.each do |line|
      stat "hw.cpu", line.split(':')[1].strip if line.include?('Version:')
    end
  end

  if section.include?("System Information")
    section.lines.each do |line|
      if line.include?('Manufacturer:')
        vendor = line.split(':')[1].gsub(" Inc.", "").strip
        stat "hw.vendor", vendor
      end

      stat "hw.model", line.split(':')[1].gsub(vendor, '').strip if line.include?('Version:')
    end
  end

  if section.include?("Chassis Information")
    section.lines.each do |line|
      stat "hw.type", line.split(':')[1].strip if line.include?("Type:")
    end
  end

  if section.include?("Memory Array Mapped Address")
    section.lines.each do |line|
      stat "hw.mem", line.split(':')[1].strip if line.include?("Range Size:")
    end
  end
end

# Reading FS to avoid firing up another ruby vm
total_gb = Dir.glob("/sys/block/{sd*,nvme*n*,mmcblk*}/size").sum do |path|
  File.read(path).to_i * 512 / 1024.0 / 1024 / 1024
end
stat "hw.disk", "#{total_gb.round(2)} GB"

# Lookup using pci.ids
def pci_name(vendor_id, device_id)
  pciids_path = "/usr/share/hwdata/pci.ids"
  return "#{vendor_id} #{device_id}" unless File.exist?(pciids_path)

  lines = File.readlines(pciids_path, chomp: true)
  vendor_name = nil

  lines.each do |line|
    if line =~ /^#{vendor_id[2..]}\s+(.*)/
      vendor_name = $1.strip
    elsif vendor_name && line =~ /^\t#{device_id[2..]}\s+(.*)/
      return "#{vendor_name} #{$1.strip}"
    end
  end

  "#{vendor_id} #{device_id}"
end

# Read GPU info from sysfs and map to name
Dir.glob("/sys/class/drm/card*/device").each do |dev|
  vendor_id = File.read(File.join(dev, "vendor")).strip rescue next
  device_id = File.read(File.join(dev, "device")).strip rescue next
  stat "hw.gpu", pci_name(vendor_id, device_id)
end
