#!/bin/bash
# Builds oo7 (the wallet's Secret Service daemon and its Secret portal)
# from an upstream release and installs it, with packaging/oo7/ applied.
# Tumbleweed's 0.4.3 has no alias paths (every Chromium/Electron app
# hangs), no partial-attribute search and takes a password only on a tty;
# its 0.6.0 still deletes the PAM socket after the first message (our
# 0001, fixed on upstream main). Not needed once a release with that fix
# is packaged.
#
#   packaging/build-oo7.sh                 build, install into /usr/local
#   packaging/build-oo7.sh --prefix DIR    install elsewhere
#
# Needs cargo and rust. The source and the build live in .oo7 at the
# repo's top; the build itself is kept in .oo7/target, so a rebuild is quick.
# c8-wallet runs $prefix/libexec/oo7-daemon when it is there; the portal's
# user unit gets a drop-in pointing it at $prefix/libexec/oo7-portal.
set -euo pipefail

version=0.6.0
sha256=793de2494423b3f3cc2457f69bca1c17ce90497dbe2eb26d9c717b1d166fee36

# The repo, one up from packaging/
top=$(cd "$(dirname "$0")/.." && pwd)
prefix=/usr/local
case "${1:-}" in
--prefix) prefix=$2 ;;
--prefix=*) prefix=${1#--prefix=} ;;
"") ;;
*) echo "usage: $0 [--prefix DIR]" >&2; exit 2 ;;
esac

command -v cargo >/dev/null || { echo "Needs cargo: zypper in cargo rust" >&2; exit 1; }

dir="$top/.oo7"
mkdir -p "$dir"
tarball="$dir/oo7-$version.tar.gz"
if ! [ -f "$tarball" ]; then
	curl -fsSL -o "$tarball.part" \
		"https://github.com/linux-credentials/oo7/archive/refs/tags/$version.tar.gz"
	mv "$tarball.part" "$tarball"
fi
echo "$sha256  $tarball" | sha256sum -c --quiet || {
	echo "oo7-$version.tar.gz isn't the release it should be" >&2
	exit 1
}
# A fresh tree with our patches (packaging/oo7/, fixes from upstream main
# not in the release yet) on top
src="$dir/src-$version"
rm -rf "$src" "$src.part"
mkdir "$src.part"
tar -xzf "$tarball" -C "$src.part" --strip-components=1
for p in "$top"/packaging/oo7/*.patch; do
	[ -e "$p" ] || continue
	patch -d "$src.part" -p1 --quiet < "$p"
done
mv "$src.part" "$src"

export CARGO_TARGET_DIR="$dir/target"
(cd "$src" && cargo build --release --locked -p oo7-daemon -p oo7-portal)

sudo=""
if ! [ -w "$prefix" ]; then
	sudo=sudo
	# No terminal (an editor, Claude's `!`): ask in a window
	if ! [ -t 0 ] && [ -n "${SUDO_ASKPASS:-}" ]; then
		sudo="sudo -A"
	fi
fi
$sudo install -Dm755 "$dir/target/release/oo7-daemon" "$prefix/libexec/oo7-daemon"
$sudo install -Dm755 "$dir/target/release/oo7-portal" "$prefix/libexec/oo7-portal"
dropin=$(mktemp)
cat > "$dropin" <<EOF
# From cont8nuum's build-oo7.sh: oo7 $version instead of the packaged one
[Service]
ExecStart=
ExecStart=$prefix/libexec/oo7-portal
EOF
$sudo install -Dm644 "$dropin" "$prefix/lib/systemd/user/oo7-portal.service.d/cont8nuum.conf"
rm -f "$dropin"
echo "oo7 $version installed into $prefix (log out and in, or restart cont8nuum-wallet)"
