#!/bin/sh
# Create the vibe-live appliance as a Proxmox LXC -- no Docker inside it.
#
#     ./create-lxc-appliance.sh 200 /var/lib/vz/template/cache/vibe-live-latest.tar.zst
#
# Run this ON the Proxmox host, as root, where `pct` exists. The template
# is what build-lxc-template.sh produced from the published image; that
# script runs somewhere with podman, this one runs here.
#
# WHAT THIS IS INSTEAD OF: create-lxc.sh, which installs Docker in the
# container and runs compose inside it. This route has no container runtime
# in the container at all -- the image's own s6 is PID 1, supervising the
# app and OvenMediaEngine. So it needs neither `nesting` nor `keyctl`, and
# the storage-driver problem on ZFS cannot happen because no storage driver
# is involved. Unprivileged either way.
#
# WHAT IT GIVES UP: caddy, and with it automatic TLS. The image serves
# plain HTTP on 8080 and has no certificate of its own, so something in
# front has to terminate TLS -- see docs/deployment/proxmox-lxc.md. That is
# the whole difference in features between the two routes.
set -eu

CTID="${1:-}"
TEMPLATE="${2:-}"
HOSTNAME="${3:-vibe-live}"
STORAGE="${STORAGE:-local-lvm}"
BRIDGE="${BRIDGE:-vmbr0}"
DISK_GB="${DISK_GB:-8}"
# /data -- the database, its key's work, recordings -- on a volume of its
# own (F111), so an update replaces the system and never moves the data
# (update-lxc-appliance.sh). Recordings live here: size it for them.
DATA_GB="${DATA_GB:-20}"
MEMORY_MB="${MEMORY_MB:-4096}"
CORES="${CORES:-4}"
# The one value nothing can generate: every URL the app hands out is built
# from it, and it has to be the name that reaches this container.
PUBLIC_BASE_URL="${PUBLIC_BASE_URL:-}"
# The container's address and gateway, set by LXC itself. **Not DHCP, and
# that is not a preference:** Proxmox's ip=dhcp is carried out by the
# container's own init running a DHCP client, and this container's init is
# s6, with no client and no `ip` to run one. Under ip=dhcp it came up with
# eth0 AND the loopback down -- the app listening and nobody, not even
# OvenMediaEngine on 127.0.0.1, able to reach it (scripts/proxmox-e2e.sh,
# Proxmox VE 9.2, 2026-10-16). Reserve the address in your router.
IP="${IP:-}"
GATEWAY="${GATEWAY:-}"

if [ -z "$CTID" ] || [ -z "$TEMPLATE" ]; then
	echo "usage: $0 <ctid> <template.tar.zst> [hostname]" >&2
	echo "" >&2
	echo "  STORAGE=$STORAGE BRIDGE=$BRIDGE DISK_GB=$DISK_GB DATA_GB=$DATA_GB" >&2
	echo "  MEMORY_MB=$MEMORY_MB CORES=$CORES" >&2
	echo "  PUBLIC_BASE_URL=${PUBLIC_BASE_URL:-<asked for if a terminal, required otherwise>}" >&2
	echo "  IP=${IP:-<asked for, e.g. 192.168.1.50/24>} GATEWAY=${GATEWAY:-<asked for, e.g. 192.168.1.1>}" >&2
	echo "" >&2
	echo "Build the template first, on a machine with podman:" >&2
	echo "  ./build-lxc-template.sh" >&2
	exit 1
fi

command -v pct >/dev/null 2>&1 || {
	echo "pct not found: run this on the Proxmox host, not inside a container." >&2
	exit 1
}

[ -f "$TEMPLATE" ] || {
	echo "No such template: $TEMPLATE" >&2
	echo "build-lxc-template.sh writes one; copy it here first." >&2
	exit 1
}

if pct status "$CTID" >/dev/null 2>&1; then
	echo "CTID $CTID already exists. Pick another, or destroy it deliberately." >&2
	exit 1
fi

if [ -z "$PUBLIC_BASE_URL" ]; then
	if [ -t 0 ]; then
		printf 'Public URL for this instance (e.g. https://live.example.org): '
		read -r PUBLIC_BASE_URL
	fi
	if [ -z "$PUBLIC_BASE_URL" ]; then
		echo "PUBLIC_BASE_URL is required: the app builds every URL it hands out from it." >&2
		exit 1
	fi
fi
# A trailing slash produces doubled slashes in the OIDC callback and in
# every link the app writes, which is the kind of thing nobody sees until a
# provider rejects a redirect_uri.
PUBLIC_BASE_URL="${PUBLIC_BASE_URL%/}"

# ask NAME PROMPT: a required value, from the environment or the terminal.
ask() {
	eval "value=\${$1}"
	if [ -z "$value" ] && [ -t 0 ]; then
		printf '%s: ' "$2"
		read -r value
	fi
	if [ -z "$value" ]; then
		echo "$1 is required: $2." >&2
		exit 1
	fi
	eval "$1=\$value"
}
ask IP "The container's address with its prefix (e.g. 192.168.1.50/24)"
ask GATEWAY "Its gateway (e.g. 192.168.1.1)"
case "$IP" in
*/*) ;;
*)
	echo "IP needs its prefix length, like 192.168.1.50/24." >&2
	exit 1
	;;
esac

# The four secrets, generated rather than chosen, each protecting something
# different -- the same set scripts/quickstart.sh writes into .env, for the
# same reasons, and the fallback exists because openssl is not on a Proxmox
# host by design.
if command -v openssl >/dev/null 2>&1; then
	secret_b64() { openssl rand -base64 32; }
	secret_hex() { openssl rand -hex 32; }
else
	secret_b64() { head -c 32 /dev/urandom | base64; }
	secret_hex() { head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n'; }
fi

# The setup code (F99), made here rather than read from the log: the
# server logs one at every start while it has no admin, but an LXC's
# output is the console, not a `logs` command. Same alphabet as the
# server's own (no 0/O, 1/I/L or U) and the same XXXX-XXXX-XXXX shape;
# spent by the claim, ignored once there is an admin.
SETUP_CODE=$(LC_ALL=C tr -dc 'ABCDEFGHJKMNPQRSTVWXYZ23456789' </dev/urandom | head -c 12 | sed 's/\(....\)\(....\)/\1-\2-/')

echo "==> creating CT $CTID ($HOSTNAME) from $TEMPLATE"
# **No --features line, and that is the point of this script.** Docker
# inside an unprivileged LXC needs nesting and keyctl; s6 supervising two
# ordinary processes needs neither.
#
# unprivileged=1 also does the uid shifting for us. Unpacking a rootfs by
# hand needs `podman unshare chown` and a matching lxc.idmap, which is the
# trap the manual version of this route documents at length -- pct create
# from a template simply does not have it.
pct create "$CTID" "$TEMPLATE" \
	--hostname "$HOSTNAME" \
	--cores "$CORES" \
	--memory "$MEMORY_MB" \
	--swap 512 \
	--rootfs "${STORAGE}:${DISK_GB}" \
	--mp0 "${STORAGE}:${DATA_GB},mp=/data" \
	--net0 "name=eth0,bridge=${BRIDGE},ip=${IP},gw=${GATEWAY}" \
	--unprivileged 1 \
	--onboot 1

CONF="/etc/pve/lxc/${CTID}.conf"
[ -f "$CONF" ] || {
	echo "pct create reported success but $CONF does not exist." >&2
	exit 1
}

echo "==> writing the configuration into $CONF"
# **lxc.environment, because the image reads its configuration from the
# environment and an LXC has no `docker run -e`.** These reach s6 as PID
# 1's environment, and `with-contenv` in each service script is what passes
# them to the app and to OvenMediaEngine -- which is why the admission
# secret below is set once and both processes agree on it.
#
# They live in the container's config, so they are readable by anybody with
# root on this host and they travel inside a vzdump. That is the same
# exposure a .env file has in the Docker route. It is worth knowing before
# handing a backup to somebody: VIBE_LIVE_DB_ENCRYPTION_KEY is in here, and
# it is the only thing that can read the credentials in the database.
{
	# **The image's init is s6's /init, not /sbin/init**, which is what
	# Proxmox starts unless told otherwise -- without this line the
	# container is created and every start fails with "Failed to exec
	# /sbin/init". Found by scripts/proxmox-e2e.sh on Proxmox VE 9.2, the
	# first time this script met a real pct (2026-10-16).
	echo "lxc.init.cmd = /init"
	# The network, brought up by LXC rather than by an init that cannot
	# (see IP above). Bringing eth0 up is also what brings the loopback up,
	# which the app and OvenMediaEngine talk over.
	echo "lxc.net.0.flags = up"
	echo "lxc.net.0.ipv4.address = ${IP}"
	echo "lxc.net.0.ipv4.gateway = ${GATEWAY}"
	echo "lxc.environment = VIBE_LIVE_PUBLIC_BASE_URL=${PUBLIC_BASE_URL}"
	echo "lxc.environment = VIBE_LIVE_DB_ENCRYPTION_KEY=$(secret_b64)"
	echo "lxc.environment = VIBE_LIVE_TOKEN_HASH_PEPPER=$(secret_hex)"
	echo "lxc.environment = VIBE_LIVE_COOKIE_SECRET=$(secret_hex)"
	# Shared with the bundled media server, which reads it as
	# OME_ADMISSION_SECRET from the same value: a mismatch rejects every
	# publish, so it is set once here rather than twice.
	echo "lxc.environment = VIBE_LIVE_OME_ADMISSION_SECRET=$(secret_hex)"
	# A way to sign in, or the process refuses to start -- deliberately,
	# since an instance nobody can sign in to looks perfectly healthy.
	# Passwords need no other software, which is why this route chooses
	# them; set the three VIBE_LIVE_OIDC_* lines instead for a provider.
	echo "lxc.environment = VIBE_LIVE_PASSWORD_LOGIN=true"
	echo "lxc.environment = VIBE_LIVE_SETUP_CODE=${SETUP_CODE}"
} >> "$CONF"

# The new volume is root's; the app runs as uid 10001 and refuses data it
# cannot write. Unprivileged, the container's ids are shifted by the
# offset its own /etc shows (100000 unless the host says otherwise).
pct mount "$CTID" >/dev/null
root="/var/lib/lxc/${CTID}/rootfs"
offset=$(stat -c %u "$root/etc")
chown "$((offset + 10001)):$((offset + 10001))" "$root/data"
pct unmount "$CTID"

echo "==> starting CT $CTID"
pct start "$CTID"

# Prove the app is actually up before claiming the container is ready --
# the same reasoning create-lxc.sh runs `hello-world` for. /livez is the
# cheapest true answer the app has, and curl is in the image because the
# compose healthcheck uses it.
echo "==> waiting for the app to answer /livez"
i=0
ok=no
while [ "$i" -lt 30 ]; do
	if pct exec "$CTID" -- curl -fsS -o /dev/null http://127.0.0.1:8080/livez 2>/dev/null; then
		ok=yes
		break
	fi
	i=$((i + 1))
	sleep 2
done

if [ "$ok" != yes ]; then
	echo "" >&2
	echo "CT $CTID started but the app never answered /livez." >&2
	echo "  pct exec $CTID -- /command/s6-rc -a list   # which services came up" >&2
	echo "  pct exec $CTID -- cat /run/s6/container_environment/VIBE_LIVE_PUBLIC_BASE_URL" >&2
	echo "A missing required variable is logged by name on startup; pct console $CTID shows it." >&2
	exit 1
fi

IP=$(pct exec "$CTID" -- hostname -I 2>/dev/null | awk '{print $1}')

cat <<DONE

CT $CTID is up at ${IP:-<no address yet>}, and the app is answering.

Claim it: open ${PUBLIC_BASE_URL}/setup (once TLS is in front, below)
and enter this setup code. It makes you the admin, signs you in, and
walks you through Settings:

  ${SETUP_CODE}

Or make the admin from here instead -- the binary needs the server's
secrets, which are in s6's copy of the container's environment, so it
runs under s6-envdir:

  pct exec $CTID -- /command/s6-envdir /run/s6/container_environment \
      vibe-live admin create <you> --admin

TLS is the one thing this route does not bring. The app serves plain HTTP
on 8080, so put a terminator in front of ${IP:-the container} and point it
at 8080 -- and make sure the name it serves is exactly
${PUBLIC_BASE_URL}, which is what the app believes it is.

Five ports have to reach ${IP:-this container} -- from the router if it is
behind one, and 80/443 arrive at your terminator rather than here:

  80/tcp     the ACME challenge, wherever your terminator wants it
  443/tcp    the site
  1936/tcp   RTMP, where OBS connects
  10000/udp  WebRTC media
  3478/tcp   WebRTC over TCP, for viewers whose network blocks UDP

The last one is the only one the instance works without: closed, a viewer
on a UDP-blocked network gets HLS instead of sub-second video and a
streamer on one cannot go live from the browser.

Then check the whole thing from outside, which is the only check that knows
whether the ports actually arrive:

  scripts/validate-setup.sh ${PUBLIC_BASE_URL}

DONE
