#!/bin/bash
# autopkgtest check: Install the rust_uno-example extension
# and test its functionality, which tests the Rust-UNO bridge, too
# (c) 2025 Software in the Public Interest, Inc.
# Authors: Rene Engelhard <rene@debian.org>

set -e
set -E

if [ -n "$AUTOPKGTEST_TMP" ]; then
        TMP=`mktemp -q -p $AUTOPKGTEST_TMP`
else
        TMP=`mktemp -q`
fi

# skip if building as root:
# unopkg errors out with "ERROR: Cannot run unopkg as root without --shared or --bundled option."
# if ran as root
if [ `id -u` = "0" ]; then
	exit 77
fi

# allow macro execution.
# The profile dir should be there since the test-extension check. if not, run a unopkg list, which should create it...
userinst=`grep UserInstallation /usr/lib/libreoffice/program/bootstraprc | cut -d= -f2 | sed -e 's,$SYSUSERCONFIG,,'`
if [ ! -d "$HOME/.config/$userinst" ]; then
	unopkg list 2>&1 >/dev/null
fi
if ! grep -q Security\/Scripting.*SecureURL $HOME/.config/$userinst/user/registrymodifications.xcu; then
	head -n-1 $HOME/.config/$userinst/user/registrymodifications.xcu > $TMP
	echo "<item oor:path=\"/org.openoffice.Office.Common/Security/Scripting\"><prop oor:name=\"SecureURL\" oor:op=\"fuse\"><value><it>file://`pwd`</it><it>file://`pwd`/debian/tests</it></value></prop></item>" >> $TMP
	echo "</oor:items>" >> $TMP
	mv $TMP $HOME/.config/$userinst/user/registrymodifications.xcu
else
	if ! grep -q file://`pwd` $HOME/.config/$userinst/user/registrymodifications.xcu; then
		sed -i "s,</it></value>,</it><it>file://`pwd`</it><it>file://`pwd`/debian/tests</it></value>," $HOME/.config/$userinst/user/registrymodifications.xcu
	fi
fi

echo "====== Call Rust UNO -> Example menu entry provided by the extension ======"
timeout -f -p 10 libreoffice --invisible --nologo --norestore \
        Test.fodt macro://./Standard.Test.TestRustUNOExample | tee $TMP

if grep -q "example completed successfully" $TMP; then
        exit 0
else
        exit 1
fi
rm $TMP

