require "set"

# The VMX records the active disk. A newer-looking filename can belong
# to another branch of the snapshot tree.
vmx = File.realpath(ARGV.fetch(0))
directory = File.dirname(vmx)
settings = File.readlines(vmx, encoding: "bom|utf-8").filter_map do |line|
  match = line.match(/^\s*([^=]+?)\s*=\s*"(.*)"\s*$/)
  [match[1].downcase, match[2]] if match
end.to_h
drives = settings.select do |key, value|
  key.match?(/\A(?:ide|scsi|sata|nvme)\d+:\d+\.filename\z/) &&
    value.downcase.end_with?(".vmdk") &&
    settings[key.sub(/filename$/, "present")].to_s.downcase == "true"
end
abort "Expected one active IDE disk at ide0:0" unless drives.keys == ["ide0:0.filename"]

def descriptor(directory, name)
  raise "Expected a local disk filename" unless File.basename(name) == name && !name.include?("\\")
  File.open(File.join(directory, name), "rb") do |disk|
    header = disk.read(512)
    raise "Invalid sparse VMDK header: #{name}" unless header&.bytesize == 512 && header.start_with?("KDMV")
    sectors, grain, offset, length = header.byteslice(12, 32).unpack("Q<4")
    unless sectors.positive? && grain.positive? && offset.positive? &&
           length.between?(1, 32) && (offset + length) * 512 <= disk.size
      raise "Invalid descriptor location: #{name}"
    end
    disk.seek(offset * 512)
    text = disk.read(length * 512).partition("\0").first
    fields = text.each_line.filter_map do |line|
      match = line.strip.match(/\A(\w+)\s*=\s*"?([^"]+?)"?\z/)
      [match[1], match[2]] if match
    end.to_h
    extent = text.match(/^RW\s+(\d+)\s+SPARSE\s+"([^"]+)"\s*$/)
    unless fields["createType"] == "monolithicSparse" && extent &&
           extent[1].to_i == sectors && extent[2] == name
      raise "Unexpected sparse extent: #{name}"
    end
    ids = fields.fetch_values("CID", "parentCID").map(&:downcase)
    raise "Invalid content ID" unless ids.all? { |id| id.match?(/\A[0-9a-f]{8}\z/) }
    { cid: ids[0], parent_id: ids[1], parent: fields["parentFileNameHint"], bytes: sectors * 512 }
  end
end

name = drives.fetch("ide0:0.filename")
seen = Set.new
expected_id = capacity = nil
loop do
  raise "Snapshot cycle at #{name}" unless seen.add?(name)
  disk = descriptor(directory, name)
  raise "Wrong parent: #{name}" if expected_id && disk[:cid] != expected_id
  capacity ||= disk[:bytes]
  raise "Capacity changed at #{name}" unless disk[:bytes] == capacity
  puts "#{name}  CID #{disk[:cid]}  parent CID #{disk[:parent_id]}"
  if disk[:parent_id] == "ffffffff"
    raise "Base disk names a parent" if disk[:parent]
    break
  end
  expected_id = disk[:parent_id]
  name = disk.fetch(:parent) || raise("Missing parent filename")
end
puts "#{seen.size} layers, #{capacity} bytes"
