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

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

if ctid.nil? || target.nil?
  warn 'Expected environment variables:'
  warn '  LXC_NAME'
  warn '  LXC_TARGET'
  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/#{Process.uid}.sock")
s.puts({ cmd: :ct_post_stop, opts: {
  id: ctid,
  pool:,
  target:
} }.to_json)
ret = JSON.parse(s.readline, symbolize_names: true)
s.close

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