#!/usr/bin/env ruby

require "json"

def read_os_id
  return nil unless File.exist?("/etc/os-release")
  File.readlines("/etc/os-release").each do |line|
    if line =~ /^ID=(.+)$/
      return $1.strip.delete('"').downcase
    end
  end
  nil
end

def read_os_name
  return nil unless File.exist?("/etc/os-release")
  File.readlines("/etc/os-release").each do |line|
    if line =~ /^PRETTY_NAME="(.+)"$/
      return $1.strip.delete('"').downcase
    end
  end
  nil
end

def ubuntu_updates
  out = `apt-get -s -o Debug::NoLocking=true upgrade 2>/dev/null`
  count = 0
  out.each_line do |line|
    count += 1 if line.start_with?("Inst ")
  end
  count
end

def ubuntu_reboot_pending
  File.exist?("/var/run/reboot-required")
end

def alma_updates
  out = `dnf -q check-update 2>/dev/null`
  status = $?.exitstatus
  return 0 if status == 0
  return nil unless status == 100
  count = 0
  out.each_line do |line|
    line = line.strip
    next if line.empty?
    next if line.start_with?("Obsoleting", "Last metadata")
    count += 1 if line.split(/\s+/).size >= 3
  end
  count
end

def alma_reboot_pending
  `dnf needs-restarting -r >/dev/null 2>&1`
  $?.exitstatus == 1
end

def df
  df_out = `df -k /`
  if df_out =~ /^\S+\s+(\d+)\s+(\d+)/
    total, used = $1.to_i, $2.to_i
    [total, used]
  end
end

result = {}
if os = read_os_id
  result["os"] = os
end
if os_name = read_os_name
  result["os_name"] = os_name
end
case os
when "ubuntu", "debian"
  result["updates"] = ubuntu_updates
  result["reboot_pending"] = ubuntu_reboot_pending
when "almalinux", "rocky", "rhel", "centos", "fedora"
  result["updates"] = alma_updates
  result["reboot_pending"] = alma_reboot_pending
end
if df_info = df
  result["df"] = df_info
end

puts JSON.generate(result)
