#!/bin/sh
# Build every component of the cont8nuum desktop, in dependency order.
#
#   ./build.sh                  build into ./.prefix, to run from the tree
#   ./build.sh --install        build for, and install into, /usr/local
#                               (your real session; sudo asks)
#   ./build.sh --prefix /usr    same, but into another prefix
#   ./build.sh --apps LIST      only these apps beside the desktop: names
#                               from files, photos, video, news, weather,
#                               tailscale, tiles, lua, cirrus, with commas
#                               between;
#                               `none` for the desktop alone (default: all)
#   ./build.sh --xr             also c8-xr: the OpenXR loader and Monado with
#                               the glasses' driver, for VR games in XR
#                               (fetched from upstream; slow the first time)
#   ./build.sh --prefix /usr --stage DIR
#                               for packaging: each component is installed
#                               under DIR/COMPONENT (DIR/compositor,
#                               DIR/apps/files, ...) instead of the prefix,
#                               and the later ones build against those
#
# The desktop is the compositor, the shell, PC settings, the toolkit, the
# theme and the live tile providers; the apps are everything else, and it
# runs without any of them. Leaving one out doesn't remove a copy that
# was installed before.
#
# The ./.prefix build lives in each component's build/, installs elsewhere
# in build-install/, so switching between them doesn't rebuild everything.
# Extra arguments go to every `meson setup`. Everything is built optimised
# with debug info (-O2 -g); C8_BUILDTYPE=debug for a build to step through.
set -eu

top=$(cd "$(dirname "$0")" && pwd)
prefix="$top/.prefix"
all_apps="lua files news tailscale weather tiles photos video cirrus"
apps=all
xr=no
stage=
while [ $# -gt 0 ]; do
	case "$1" in
	--apps) apps=$2; shift 2 ;;
	--apps=*) apps=${1#--apps=}; shift ;;
	--install) prefix=/usr/local; shift ;;
	--xr) xr=yes; shift ;;
	--stage) stage=$2; shift 2 ;;
	--stage=*) stage=${1#--stage=}; shift ;;
	--prefix) prefix=$2; shift 2 ;;
	--prefix=*) prefix=${1#--prefix=}; shift ;;
	*) break ;;
	esac
done

sudo=""
case "$stage" in
'') ;;
/*) mkdir -p "$stage" ;;
*) echo "build.sh: --stage needs an absolute path" >&2; exit 2 ;;
esac
case "$prefix" in
"$top"/*) builddir=build ;;
*)
	builddir=build-install
	# Packages get their own, set up afresh: one made for another
	# prefix keeps what it found then (wlroots in /usr/local)
	[ -z "$stage" ] || builddir=build-stage
	[ -n "$stage" ] || [ -w "$prefix" ] || sudo=sudo
	# No terminal to ask on (run from an editor or Claude's `!`): ask
	# for the password in a window instead
	if [ -n "$sudo" ] && ! [ -t 0 ]; then
		for a in "${SUDO_ASKPASS:-}" "$prefix/bin/c8-askpass" \
				/usr/libexec/ssh/ksshaskpass \
				/usr/bin/ksshaskpass /usr/libexec/ssh/ssh-askpass; do
			if [ -n "$a" ] && [ -x "$a" ]; then
				export SUDO_ASKPASS="$a"
				sudo="sudo -A"
				break
			fi
		done
	fi
	;;
esac

case "$apps" in
all) apps=$all_apps ;;
none) apps= ;;
*) apps=$(echo "$apps" | tr ',' ' ') ;;
esac
for a in $apps; do
	case " $all_apps " in
	*" $a "*) ;;
	*)
		echo "build.sh: no app called '$a' (there are: $all_apps)" >&2
		exit 2
		;;
	esac
done
# In dependency order, as paths under the top: the desktop's parts, with
# the chosen apps (in their own order) before the shell. Lua's apps need
# its runtime, which is only built for them.
components="protocols theme toolkit/c8ui compositor desktop/widgets desktop/settings"
for a in $all_apps; do
	case " $apps " in
	*" $a "*)
		[ "$a" = lua ] && components="$components toolkit/lua"
		components="$components apps/$a"
		;;
	esac
done
components="$components desktop/shell"

# Where meson puts the prefix's libraries: lib64 on openSUSE and Fedora,
# lib/x86_64-linux-gnu (the multiarch name) on Debian and Ubuntu
multiarch=$(${CC:-cc} -print-multiarch 2>/dev/null || true)
libdirs="$prefix/lib64:${multiarch:+$prefix/lib/$multiarch:}$prefix/lib"
pcdirs=
for d in $(echo "$libdirs" | tr : ' '); do pcdirs="$pcdirs$d/pkgconfig:"; done
export PKG_CONFIG_PATH="$pcdirs$prefix/share/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}"
# Staged, the components are found through copies of their .pc files
# whose prefix is where they were staged (pkgconf's own relocation
# guesses the prefix from the folder, which multiarch libdirs defeat).
# Copies only: the staged .pc files themselves keep the real prefix.
if [ -n "$stage" ]; then
	stagepc=$stage/.pkgconfig
	mkdir -p "$stagepc"
	export PKG_CONFIG_PATH="$stagepc:$PKG_CONFIG_PATH"
fi
# and their libraries through LD_LIBRARY_PATH, which is where the linker
# looks for a staged library's own libraries (not -L)
restage() { # what was just installed, under $stage
	find "$1" -name '*.pc' -path '*/pkgconfig/*' | while read -r pc; do
		sed "s|^prefix=$prefix\$|prefix=$1$prefix|" "$pc" > "$stagepc/$(basename "$pc")"
	done
	for d in $(find "$1" -name 'lib*.so' -printf '%h\n' | sort -u); do
		LD_LIBRARY_PATH="$d${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
	done
	export LD_LIBRARY_PATH
}
# Libraries newer than the distribution's, built by packaging/private-libs.sh
# (a folder each)
if [ -n "$stage" ]; then
	for d in "$stage"/private/*/; do
		[ -d "$d" ] && restage "${d%/}"
	done
fi

# Where the cont8nuum account's site is (C8_ACCOUNT_URL). Unset: the
# nested build gets the local test site, so a test session never syncs
# into the real account, and any other build the live one,
# c8.lowtide.sbs. The local test site only for the nested build: on an
# installed desktop plain http on a port anyone on the machine can
# listen on would be handed the account's tokens and what sync applies.
# Empty: the account isn't offered.
if [ "$prefix" = "$top/.prefix" ]; then
	account_url=${C8_ACCOUNT_URL-http://127.0.0.1:8088}
else
	account_url=${C8_ACCOUNT_URL-https://c8.lowtide.sbs}
fi

# First: c8 builds its OpenXR overlay (xrclient.c) only with the
# loader's headers in the prefix
if [ "$xr" = yes ]; then
	suffix=""
	[ "$builddir" = build-install ] && suffix=-install
	[ -z "$stage" ] || { echo "build.sh: --xr can't be staged yet" >&2; exit 2; }
	C8_SUDO="$sudo" "$top/xr/build.sh" "$prefix" "$suffix"
fi

for c in $components; do
	echo "==> $c"
	cd "$top/$c"
	# Said every time: a build dir set up before keeps the type it had,
	# and meson's own default is no optimisation at all
	own="-Dbuildtype=${C8_BUILDTYPE:-debugoptimized}"
	[ "$c" = desktop/settings ] && own="$own -Daccount_url=$account_url"
	re=
	[ -z "$stage" ] || rm -rf "$builddir"
	[ -d "$builddir" ] && re=--reconfigure
	# Quiet, but not when it fails: meson says why on stdout
	log=$(mktemp)
	if ! meson setup $re "$builddir" --prefix "$prefix" $own "$@" >"$log" 2>&1; then
		tail -25 "$log" >&2
		rm -f "$log"
		exit 1
	fi
	rm -f "$log"
	ninja -C "$builddir"
	# --no-rebuild so nothing gets compiled as root; a subproject (the Lua
	# built into c8-lua) is ours to link, not to install
	if [ -n "$stage" ]; then
		DESTDIR="$stage/$c" meson install -C "$builddir" --no-rebuild --skip-subprojects >/dev/null
		restage "$stage/$c"
	else
		$sudo meson install -C "$builddir" --no-rebuild --skip-subprojects >/dev/null
	fi
done

if [ -n "$stage" ]; then
	rm -rf "$stagepc"
	echo
	echo "Staged for $prefix in $stage, a folder per component."
	exit 0
fi

if [ "$prefix" = "$top/.prefix" ]; then
	cat <<EOF

Built into $prefix. To try it nested in your session:

  export PATH="$prefix/bin:\$PATH" LD_LIBRARY_PATH="$libdirs"
  export XDG_DATA_DIRS="$prefix/share:\${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
  c8

To install it for your real session: ./build.sh --install
EOF
else
	# meson doesn't always refresh the linker cache, and without it nothing
	# finds the freshly installed libc8ui
	[ -x /sbin/ldconfig ] && $sudo /sbin/ldconfig
	# The session bus only reads its service files at start: make it see
	# new ones (the Files portal backend) without logging out
	busctl --user call org.freedesktop.DBus /org/freedesktop/DBus \
		org.freedesktop.DBus ReloadConfig >/dev/null 2>&1 || true
	cat <<EOF

Installed into $prefix. Log out and pick cont8nuum in SDDM to use it.
EOF
fi
