#!/bin/sh
# denv sidecar installer.
#
#   curl -fsSL https://get.denv.ai | sh -s -- --token <join token> [--server URL] [--zfs-pool POOL] [--data DIR]
#
# Downloads denvd for this machine's architecture, installs it to
# /usr/local/bin, and runs `denvd install`, which writes a systemd unit, joins
# the control plane with the token, and starts the service. denvd only ever
# dials out; nothing listens. Re-running with the same token is refused by the
# control plane (tokens are single-use); re-running without a token keeps the
# host's saved identity.
set -eu

SERVER="${DENV_SERVER:-https://api.denv.ai}"
RELEASES="${DENV_RELEASES:-https://get.denv.ai}"
TOKEN="${DENV_JOIN_TOKEN:-}"
POOL="${DENV_ZFS_POOL:-}"
DATA="${DENV_DATA_DIR:-}"
BIN_DIR="${DENV_BIN_DIR:-/usr/local/bin}"

while [ $# -gt 0 ]; do
  case "$1" in
    --token) TOKEN="$2"; shift 2 ;;
    --server) SERVER="$2"; shift 2 ;;
    --zfs-pool) POOL="$2"; shift 2 ;;
    --data) DATA="$2"; shift 2 ;;
    --releases) RELEASES="$2"; shift 2 ;;
    -h|--help) sed -n '2,10p' "$0"; exit 0 ;;
    *) echo "install.sh: unknown flag $1" >&2; exit 2 ;;
  esac
done

if [ "$(uname -s)" != "Linux" ]; then
  echo "install.sh: denvd runs on Linux hosts (this is $(uname -s))" >&2
  exit 1
fi
case "$(uname -m)" in
  x86_64|amd64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) echo "install.sh: unsupported architecture $(uname -m)" >&2; exit 1 ;;
esac
if [ "$(id -u)" -ne 0 ]; then
  echo "install.sh: run as root (sudo) so denvd can install its service and manage Docker" >&2
  exit 1
fi
if ! command -v docker >/dev/null 2>&1; then
  echo "install.sh: Docker is required on the host (https://docs.docker.com/engine/install/)" >&2
  exit 1
fi

URL="$RELEASES/denvd-linux-$ARCH"
TMP="$(mktemp)"
trap 'rm -f "$TMP"' EXIT
echo "downloading $URL"
if command -v curl >/dev/null 2>&1; then
  curl -fsSL "$URL" -o "$TMP"
elif command -v wget >/dev/null 2>&1; then
  wget -qO "$TMP" "$URL"
else
  echo "install.sh: need curl or wget" >&2
  exit 1
fi
chmod 0755 "$TMP"
mkdir -p "$BIN_DIR"
mv "$TMP" "$BIN_DIR/denvd"
trap - EXIT
echo "installed $BIN_DIR/denvd ($("$BIN_DIR/denvd" version 2>/dev/null || echo unknown))"

set -- --server "$SERVER"
[ -n "$TOKEN" ] && set -- "$@" --token "$TOKEN"
[ -n "$POOL" ] && set -- "$@" --zfs-pool "$POOL"
[ -n "$DATA" ] && set -- "$@" --data "$DATA"
exec "$BIN_DIR/denvd" install "$@"
