#!/bin/bash
# Jabali Panel — nspawn enter helper.
#
# Sudo-bridged from /usr/local/bin/jabali-ssh-shell. Runs as root via
# /etc/sudoers.d/jabali-nspawn (NOPASSWD, locked to this absolute path).
# Validates inputs, then exec's systemd-nspawn --ephemeral against the
# pinned image with the calling user's home bind-mounted in.
#
# Args: <image-name>
#   image-name must match ^[a-z0-9-]+$ and a directory must exist at
#   /var/lib/jabali-nspawn/images/<image-name>.

set -eu

readonly IMAGES_DIR=/var/lib/jabali-nspawn/images
readonly WRAPPER_PATH=/usr/local/bin/jabali-ssh-shell
readonly NSPAWN=/usr/bin/systemd-nspawn

# Sudo populates SUDO_USER with the original calling user. Refuse if it
# isn't a real hosting user with our wrapper as their login shell.
if [ -z "${SUDO_USER:-}" ]; then
  echo "jabali-nspawn-enter: must be invoked via sudo" >&2
  exit 1
fi

PASSWD_LINE=$(getent passwd "${SUDO_USER}" || true)
if [ -z "${PASSWD_LINE}" ]; then
  echo "jabali-nspawn-enter: caller ${SUDO_USER} not in passwd" >&2
  exit 1
fi
USER_SHELL=$(echo "${PASSWD_LINE}" | cut -d: -f7)
if [ "${USER_SHELL}" != "${WRAPPER_PATH}" ]; then
  echo "jabali-nspawn-enter: caller ${SUDO_USER} shell is not ${WRAPPER_PATH}" >&2
  exit 1
fi

USER_HOME=$(echo "${PASSWD_LINE}" | cut -d: -f6)
if [ -z "${USER_HOME}" ] || [ ! -d "${USER_HOME}" ]; then
  echo "jabali-nspawn-enter: home dir for ${SUDO_USER} not found" >&2
  exit 1
fi

# Validate image arg shape and existence.
if [ "$#" -ne 1 ]; then
  echo "jabali-nspawn-enter: usage: $0 <image-name>" >&2
  exit 1
fi
IMAGE_NAME="$1"
case "${IMAGE_NAME}" in
  ''|*[!a-z0-9-]*)
    echo "jabali-nspawn-enter: invalid image name" >&2
    exit 1
    ;;
esac
IMAGE_PATH="${IMAGES_DIR}/${IMAGE_NAME}"
if [ ! -d "${IMAGE_PATH}" ]; then
  echo "jabali-nspawn-enter: image ${IMAGE_NAME} not found" >&2
  exit 1
fi

# Allow-list image name against actual on-disk directory listing too —
# guards against the (impossible-via-sudoers) case of a CVE letting
# arbitrary args through.
FOUND=0
for entry in "${IMAGES_DIR}"/*; do
  [ -d "${entry}" ] || continue
  if [ "$(basename "${entry}")" = "${IMAGE_NAME}" ]; then
    FOUND=1
    break
  fi
done
if [ "${FOUND}" -ne 1 ]; then
  echo "jabali-nspawn-enter: image ${IMAGE_NAME} not in allowlist" >&2
  exit 1
fi

# systemd-nspawn ephemeral overlay; user's home rw'd in; no host
# sockets bound (ADR-0067 §0.14). --as-pid2 keeps signal semantics
# correct. --link-journal=no keeps tenant logs out of host journal.
exec "${NSPAWN}" \
  --quiet \
  --ephemeral \
  --directory="${IMAGE_PATH}" \
  --bind="${USER_HOME}:${USER_HOME}" \
  --chdir="${USER_HOME}" \
  --setenv="HOME=${USER_HOME}" \
  --setenv="USER=${SUDO_USER}" \
  --setenv="LOGNAME=${SUDO_USER}" \
  --link-journal=no \
  --register=no \
  --as-pid2 \
  /bin/bash --login
