#!/bin/sh
CARGO_TARGET_DIR=${CARGO_TARGET_DIR:-${PWD}/target}
POLICY_PATH=${POLICY_PATH:-/opt/kumomta/etc/policy/init.lua}

KUMOD=${KUMOD:-kumod}

if ! test -x ${KUMOD} ; then
  for candidate in /opt/kumomta/sbin/kumod "${CARGO_TARGET_DIR}/release/kumod" "${CARGO_TARGET_DIR}/debug/kumod" ; do
    if test -x "${candidate}" ; then
      KUMOD="${candidate}"
      break;
    fi
  done

  if ! test -x "${KUMOD}" ; then
    echo "Couldn't find kumod"
    exit 1
  fi
fi

script=$(mktemp)
trap "rm -f -- '$script'" EXIT
cat >${script} <<-EOT
local kumo = require 'kumo'
dofile "${POLICY_PATH}"

kumo.on('main', function(domain, source)
  if domain == nil or domain == '--help' or domain == '-h' then
      print [[
Resolves the effective shaping configuration for a domain
and optionally for the source that you specify.

The config is shown as a json object dump.

resolve-shaping-domain DOMAIN_NAME [SOURCE_NAME]

If SOURCE_NAME is omitted, 'unspecified' will be used
for the source name.
]]
      if domain == nil then
        os.exit(1)
      end
      return
  end

  local source = source or 'unspecified'

  local site_name = domain
  local ok, mx = pcall(kumo.dns.lookup_mx, domain)
  if ok then
    site_name = mx.site_name
  end

  local path_config = kumo.invoke_get_egress_path_config(
    domain,
    source,
    site_name
  )
  print(kumo.serde.json_encode_pretty(path_config))
end)
EOT

is_user_root () { [ "${EUID:-$(id -u)}" -eq 0 ]; }

RUN_AS_USER=""
if is_user_root ; then
  chmod a+rx $script
  RUN_AS_USER="--user kumod"
fi

${KUMOD} $RUN_AS_USER --policy $script --script -- "$@"


