#!/bin/sh
# `cloutctl` — the shim that makes the unzipped bundle a command.
#
# The README in the zip said `node cloutctl.js`, so every worked example an
# operator copied began with `node`, `which cloutctl` answered nothing, and a
# systemd unit had to hardcode both the interpreter and the install path. This
# file is what turns the directory into something you can put on PATH:
#
#     unzip cloutctl-0.0.14.zip -d /opt
#     ln -s /opt/cloutctl-0.0.14/cloutctl /usr/local/bin/cloutctl
#     cloutctl --version
#
# Two properties, both deliberate:
#
#  * **It resolves its own directory through the symlink.** `readlink -f` (and
#    the loop below where that is unavailable) is what lets the link live in
#    /usr/local/bin while `cloutctl.js` stays in /opt beside `build-info.json`,
#    which `--version` reads as a sibling of the module.
#  * **`exec`, not a subshell.** The signal handling in `system serve` is the
#    whole point of `--pidfile`: a wrapper process between systemd and Node
#    would take the SIGTERM itself and leave the server undrained, which is the
#    failure the daemon work exists to remove.
#
# `CLOUTCTL_NODE` overrides the interpreter for a box whose `node` on PATH is
# older than 24 — the version `doctor` checks and `node:sqlite` requires.
set -e

target=$0
# Follow symlinks without depending on GNU readlink, which macOS does not have.
while [ -L "$target" ]; do
  link=$(ls -ld -- "$target" | sed -e 's/.* -> //')
  case $link in
    /*) target=$link ;;
    *) target=$(dirname -- "$target")/$link ;;
  esac
done
here=$(cd -- "$(dirname -- "$target")" && pwd -P)

node_bin=${CLOUTCTL_NODE:-node}
if ! command -v "$node_bin" >/dev/null 2>&1; then
  echo "cloutctl: no '$node_bin' on PATH. Node 24 or later is required (the store is node:sqlite)." >&2
  echo "cloutctl: set CLOUTCTL_NODE=/path/to/node to name one." >&2
  exit 1
fi

exec "$node_bin" "$here/cloutctl.js" "$@"
