#!/usr/bin/env ruby
require 'json'
require 'socket'

ctid = ENV.fetch('LXC_NAME', nil)

if ctid.nil?
  warn 'Expected environment variables:'
  warn '  LXC_NAME'
  exit(false)
end

if %r{^/run/osctl/pools/([^/]+)/hooks} !~ $0
  warn "Unable to detect pool name from '#{$0}'"
  exit(false)
end

pool = Regexp.last_match(1)

s = UNIXSocket.new('/run/osctl/user-control/namespaced.sock')
s.puts({ cmd: :ct_pre_mount, opts: {
  id: ctid,
  pool:,
  rootfs_mount: ENV.fetch('LXC_ROOTFS_MOUNT', nil)
} }.to_json)
ret = JSON.parse(s.readline, symbolize_names: true)
s.close

exit if ret[:status]
warn "Error: #{ret[:message]}"
exit(false)
