require "open3"

# A raw export of the one-partition MBR disk used in this article.
class XpVolume
  BLOCK = 65_536
  CLUSTER = 4096
  F_PUNCHHOLE = 99 # macOS sys/fcntl.h, fpunchhole_t

  def initialize(path)
    File.open(path, "rb") do |image|
      mbr = image.read(512)
      raise "Missing MBR signature" unless mbr&.byteslice(510, 2) == "\x55\xaa".b
      entries = 4.times.map { |i| mbr.byteslice(446 + i * 16, 16) }
      entries.reject! { |entry| entry.getbyte(4).zero? }
      raise "Expected one type 7 MBR partition" unless entries.size == 1 && entries.first.getbyte(4) == 7
      @sector, sectors = entries.first.byteslice(8, 8).unpack("V2")
      @start = @sector * 512
      raise "Invalid partition bounds" unless @sector.positive? && @start + sectors * 512 <= image.size
      boot = image.pread(512, @start)
      unless boot.byteslice(3, 8) == "NTFS    " && boot.unpack1("@11v") == 512 && boot.getbyte(13) == 8
        raise "Expected NTFS with 512-byte sectors and 4 KiB clusters"
      end
      volume_sectors = boot.unpack1("@40Q<")
      raise "Invalid NTFS length" unless volume_sectors.between?(1, sectors)
      @limit = @start + volume_sectors * 512
    end
    # NTFS record 3, attribute 112 holds volume flags. Record 6's
    # unnamed data stream (128) holds one allocation bit per cluster.
    flags = attribute(path, "3-112")
    raise "Missing flags or dirty volume" unless flags.bytesize >= 12 && (flags.unpack1("@10v") & 1).zero?
    @bitmap = attribute(path, "6-128")
    raise "Short NTFS bitmap" if @bitmap.bytesize * 8 * CLUSTER < @limit - @start - CLUSTER
  end

  def attribute(path, address)
    bytes, error, status = Open3.capture3("icat", "-i", "raw", "-f", "ntfs", "-o", @sector.to_s, path, address, binmode: true)
    raise "icat failed for #{address}: #{error}" unless status.success?
    bytes
  end

  def free_ranges
    # A zero bitmap byte covers eight free clusters. Round inward to
    # QCOW2 block boundaries and preserve the ends of the partition.
    @bitmap.scan(/\x00{2,}/n) do
      match = Regexp.last_match
      low = [@start + match.begin(0) * 8 * CLUSTER, @start + BLOCK].max
      high = [@start + match.end(0) * 8 * CLUSTER, @limit - BLOCK].min
      first = ((low + BLOCK - 1) / BLOCK) * BLOCK
      finish = (high / BLOCK) * BLOCK
      yield first, finish - first if finish > first
    end
  end

  def release(path)
    File.open(path, "r+b") do |copy|
      free_ranges do |offset, length|
        copy.fcntl(F_PUNCHHOLE, [0, 0, offset, length].pack("L2q2"))
      end
      copy.fsync
    end
  end

  def free_block?(offset)
    return false if offset < @start || offset + BLOCK > @limit
    first = (offset - @start) / CLUSTER
    last = (offset + BLOCK - 1 - @start) / CLUSTER
    (first..last).all? { |i| (@bitmap.getbyte(i / 8) & (1 << (i % 8))).zero? }
  end

  def verify(original, work)
    zero = "\0".b * BLOCK
    File.open(original, "rb") do |source|
      File.open(work, "rb") do |copy|
        raise "Disk length changed" unless source.size == copy.size
        while (old = source.read(4 * 1024 * 1024))
          offset = source.pos - old.bytesize
          new_bytes = copy.read(old.bytesize)
          next if old == new_bytes
          (0...old.bytesize).step(BLOCK) do |i|
            block = new_bytes.byteslice(i, BLOCK)
            next if block == old.byteslice(i, BLOCK)
            raise "Unexpected change at #{offset + i}" unless block == zero && free_block?(offset + i)
          end
        end
      end
    end
  end
end
