#!/usr/bin/env bash
# W3BS OS for virtual machines: turn a running Debian 13 (or other Debian-based) system into
# W3BS OS, without touching its disk layout, boot loader, network or SSH, which the VM's
# manager (Lima, devvm) owns. Served at https://w3bs.org/os/convert.sh.
#
#   curl -fsSL https://w3bs.org/os/convert.sh | sudo bash -s -- --user "$USER"
#
# It does the "W3BS" part of the ISO installer (os/debian/.../w3bs-os-install): the release
# file, the motd, zsh as the login shell, the PATH for mise and pnpm, and for the user the
# w3bs CLI, mise with node, bun and pnpm, readm3, hqterm and ThreatCrush. The installer's
# own parts that a VM manager does (partitions, LUKS, GRUB, systemd-networkd) are left out.
#
# Two parts, so a VM manager can run each where it fits:
#   --part system   as root: packages, release file, motd, PATH, login shell (needs --user)
#   --part user     as the user: w3bs CLI and the developer tools in their home
#   --part all      both (the default; run as root with --user)
set -euo pipefail

VERSION_URL=https://w3bs.org/os/version
EDITION=vm
PART=all
TARGET_USER=""
SHELL_ZSH=1
DEV_TOOLS=1
LOG=/var/log/w3bs-os-convert.log

usage() {
	cat <<'EOF'
usage: convert.sh [--user NAME] [--part all|system|user] [--edition NAME]
                  [--keep-shell] [--no-dev-tools]

  --user NAME      the person's account (default: $SUDO_USER, else the first uid >= 1000)
  --part PART      all (default), system (root only) or user (the account only)
  --edition NAME   recorded in /etc/w3bs-os-release as EDITION (lima, devvm, vm)
  --keep-shell     leave the login shell as it is (devvm's prompt lives in bash)
  --no-dev-tools   only the w3bs CLI: no mise, node, bun, pnpm, readm3, hqterm, threatcrush
EOF
}

say() { printf '==> %s\n' "$*"; }
warn() { printf 'warning: %s\n' "$*" >&2; }
die() { printf 'convert.sh: %s\n' "$*" >&2; exit 1; }

# --- system part (root) -------------------------------------------------------------------
system_part() {
	[ "$(id -u)" = 0 ] || die "the system part needs root (sudo)"
	[ -r /etc/os-release ] || die "no /etc/os-release"
	# shellcheck disable=SC1091
	. /etc/os-release
	case " ${ID:-} ${ID_LIKE:-} " in *" debian "*) ;; *) die "W3BS OS needs a Debian-based system; this is ${PRETTY_NAME:-unknown}" ;; esac
	[ "${ID:-}" = debian ] && [ "${VERSION_ID:-}" != 13 ] && warn "W3BS OS 1.2 is Debian 13; this is Debian ${VERSION_ID:-?}"
	if [ -z "$TARGET_USER" ]; then
		TARGET_USER=${SUDO_USER:-}
		[ -n "$TARGET_USER" ] || TARGET_USER=$(awk -F: '$3 >= 1000 && $3 < 60000 { print $1; exit }' /etc/passwd)
	fi
	[ -n "$TARGET_USER" ] && id "$TARGET_USER" >/dev/null 2>&1 || die "no such user: ${TARGET_USER:-none} (give --user)"

	say "Packages (zsh, git, curl and friends)"
	export DEBIAN_FRONTEND=noninteractive
	apt-get update -qq
	# libatomic1: Node 26's prebuilt binary needs libatomic.so.1, which minimal Debian 13
	# images (genericcloud, slim) leave out, so `mise use node@lts` fails without it.
	apt-get install -y -qq --no-install-recommends \
		zsh bash curl wget ca-certificates git less sudo locales unzip xz-utils procps libatomic1 >/dev/null

	say "W3BS OS release file and motd"
	local os_version
	os_version=$(curl -fsSL -m 20 "$VERSION_URL" 2>/dev/null | tr -cd '0-9A-Za-z.+-' | head -c 32 || true)
	cat >/etc/w3bs-os-release <<EOF
ID=w3bs-os
NAME="W3BS OS"
VERSION=${os_version:-1.2}
EDITION=$EDITION
BASE=${ID:-debian}
BASE_VERSION=$(cat /etc/debian_version 2>/dev/null || echo "${VERSION_ID:-}")
EOF
	cat >/etc/motd <<'EOF'

  Welcome to W3BS OS (Debian 13 based).   https://w3bs.org/os

    w3bs install <package>  any package on w3bs.org/packages
    mise use -g node@lts    language runtimes (bun, pnpm are set up)

EOF

	say "PATH for mise and pnpm"
	cat >/etc/profile.d/w3bs-dev.sh <<'EOF'
# W3BS OS: mise-managed tools and pnpm global commands on PATH.
export PNPM_HOME="$HOME/.local/share/pnpm"
case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) PATH="$HOME/.local/bin:$PATH" ;; esac
case ":$PATH:" in *":$HOME/.local/share/mise/shims:"*) ;; *) PATH="$HOME/.local/share/mise/shims:$PATH" ;; esac
case ":$PATH:" in *":$PNPM_HOME:"*) ;; *) PATH="$PNPM_HOME:$PATH" ;; esac
export PATH
EOF
	mkdir -p /etc/zsh
	grep -qs w3bs-dev /etc/zsh/zprofile || echo '[ -r /etc/profile.d/w3bs-dev.sh ] && . /etc/profile.d/w3bs-dev.sh' >>/etc/zsh/zprofile

	if [ -n "$SHELL_ZSH" ]; then
		say "zsh is $TARGET_USER's login shell"
		chsh -s /usr/bin/zsh "$TARGET_USER"
		local home
		home=$(getent passwd "$TARGET_USER" | cut -d: -f6)
		[ -e "$home/.zshrc" ] || install -o "$TARGET_USER" -g "$(id -gn "$TARGET_USER")" -m 0644 /dev/null "$home/.zshrc"
	fi
}

# --- user part (the account) --------------------------------------------------------------
user_script() {
	cat <<EOF
set -eu
export PATH="\$HOME/.local/share/pnpm:\$HOME/.local/share/mise/shims:\$HOME/.local/bin:\$PATH"
curl -fsSL https://w3bs.org/install.sh | W3BS_YES=1 sh
w3bs --version
[ -n "$DEV_TOOLS" ] || exit 0
command -v mise >/dev/null 2>&1 || curl -fsSL https://mise.run | sh
export MISE_YES=1 PNPM_HOME="\$HOME/.local/share/pnpm"
mise use -g node@lts bun@latest npm:pnpm@latest
mise reshim
pnpm config set global-bin-dir "\$PNPM_HOME"
pnpm i -g @profullstack/readm3 || echo "warning: readm3 did not install" >&2
w3bs install --yes --non-interactive hqterm.sh/hqterm threatcrush.com/threatcrush || echo "warning: hqterm or threatcrush did not install" >&2
mise reshim
node --version; bun --version; pnpm --version
EOF
}
user_part() {
	if [ "$(id -u)" = 0 ]; then
		[ -n "$TARGET_USER" ] || die "give --user for the user part"
		say "w3bs CLI and developer tools for $TARGET_USER"
		su - "$TARGET_USER" -s /bin/sh -c "$(user_script)"
	else
		say "w3bs CLI and developer tools for $(id -un)"
		sh -c "$(user_script)"
	fi
}

main() {
	while [ $# -gt 0 ]; do
		case "$1" in
			--user) TARGET_USER=${2:?--user needs a name}; shift ;;
			--part) PART=${2:?--part needs all, system or user}; shift ;;
			--edition) EDITION=${2:?--edition needs a name}; shift ;;
			--keep-shell) SHELL_ZSH="" ;;
			--no-dev-tools) DEV_TOOLS="" ;;
			-h|--help) usage; exit 0 ;;
			*) echo "convert.sh: unknown option $1" >&2; usage >&2; exit 2 ;;
		esac
		shift
	done
	case "$PART" in all|system|user) ;; *) die "--part is all, system or user" ;; esac
	if [ "$PART" != user ] && [ "$(id -u)" = 0 ]; then
		mkdir -p "$(dirname "$LOG")"
		exec > >(tee -a "$LOG") 2>&1
	fi
	case "$PART" in
		system) system_part ;;
		user) user_part ;;
		all) system_part; user_part ;;
	esac
	[ "$PART" = user ] || say "W3BS OS is set up ($EDITION). Log in again to get zsh and the new PATH."
}

# Nothing runs until this last line, so a download cut short (curl | sudo bash) does nothing.
main "$@"
