#!/usr/bin/env ruby

$host = File.read("/etc/hostname").chomp
def stat(key, val = '')
  puts "#{$host}.#{key} #{val}"
end

stat "net.host", $host
stat "net.ipv4", `ip route`.lines.select { _1.include?('192') }.first.split(' ')[8]
stat "net.ipv6", ''

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?('Family:')
    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?('Product Name:')
    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
end

cmd_queue = Dir.children("/srv/secure/cmd/queue").sort
stat "cmd.status", File.read("/srv/secure/cmd/status").chomp
stat "cmd.queue", cmd_queue.join(",")
stat "cmd.count", cmd_queue.size

has_bat = false
pattern = "Device: /org/freedesktop/UPower/devices/battery_"
`upower -d`.split("\n\n").find { _1.start_with?(pattern) }&.lines&.each do |line|
  has_bat = true
  stat "bat.state", line.split(":")[1].strip if line.include?("state")
  stat "bat.percentage", "#{line.split(':')[1].to_i}%" if line.include?("percentage")
  stat "bat.time", line.split(":")[1].strip.gsub(' hours', 'h').gsub(' minutes', 'm') if line.include?("time")
end
unless has_bat
  stat "bat.state", "none"
end

vol_left, vol_right = `pactl get-sink-volume @DEFAULT_SINK@`
  .lines.first&.gsub('Volume: ', '')&.split(',')&.map { _1.split('/')[1].strip } || %w[0% 0%]
stat "vol.left.percentage", vol_left
stat "vol.right.percentage", vol_right
stat "vol.percentage", "#{vol_left.to_i + vol_right.to_i / 2}%"

part = `df /var/btrfs`.lines[1].split.first
disk = `lsblk -no pkname #{part}`.chomp
stat "disk.size", `lsblk -no SIZE /dev/#{disk}`.lines.first.chomp
stat "disk.used", ''

report = `/opt/admin/bin/tl-comp-report`.lines.each { stat(*_1.split) }
