#!/usr/bin/ruby.ruby3.3 
# frozen_string_literal: true
# Copyright (C) 2018 mwrap hackers <mwrap-public@80x24.org>
# License: GPL-2.0+ <https://www.gnu.org/licenses/gpl-2.0.txt>
require 'mwrap'
mwrap_so = $".grep(%r{/mwrap\.so\z})[0] or abort "mwrap.so not loaded"
cur = ENV['LD_PRELOAD']
if cur
  cur = cur.split(/[:\s]+/)
  if !cur.include?(mwrap_so)
    # drop old versions
    cur.delete_if { |path| path.end_with?('/mwrap.so') }
    cur.unshift(mwrap_so)
    ENV['LD_PRELOAD'] = cur.join(':')
  end
else
  ENV['LD_PRELOAD'] = mwrap_so
end

# work around close-on-exec by default behavior in Ruby:
opts = {}
if ENV['MWRAP'] =~ /dump_fd:(\d+)/
  dump_fd = $1.to_i
  if dump_fd > 2
    dump_io = IO.new(dump_fd)
    opts[dump_fd] = dump_io
  end
end

# allow inheriting FDs from systemd
n = ENV['LISTEN_FDS']
if n && ENV['LISTEN_PID'].to_i == $$
  n = 3 + n.to_i
  (3...n).each { |fd| opts[fd] = IO.new(fd) }
end
exec *ARGV, opts
