#!/bin/bash
#
# Compile InkScape under Syd under Perf.
#
# Copyright 2024 Ali Polatel <alip@chesswob.org>
#
# SPDX-License-Identifier: GPL-3.0

if [[ ${#} -lt 1 ]]; then
    echo >&2 "Usage: ${0##*/} <perf-arguments>..."
    exit 1
fi

# Make sure we don't trigger TPE.
umask 077

# Disable coredumps.
ulimit -c 0

SYD="${CARGO_BIN_EXE_syd:-syd}"
PERF="${PERF:-perf}"
PROF="${SYD_PERF_PROFILE:-paludis}"

DIR="$(mktemp -d --tmpdir=/tmp syd-ink.XXXXXXXXXX)"
[[ -d "${DIR}" ]] || exit 2

CWD=$(readlink -f ${PWD})
trap "mv '${DIR}'/inkscape/perf.data* '${CWD}' &>/dev/null && rm -rf '${DIR}'" INT TERM EXIT
set -ex

pushd "${DIR}"
git clone --depth 1 --recursive https://gitlab.com/inkscape/inkscape.git

pushd inkscape
rm -f /tmp/syd.pid
export SYD_PID_FN=/tmp/syd.pid
"${PERF}" "${@}" -- \
    "${SYD}" -q -p"${PROF}" -pP -m 'allow/all+/***' -mlock:on \
        -- bash -ex <<'EOF'
export CFLAGS="-O2 -march=native -mtune=native -flto"
export CXXFLAGS="-O2 -march=native -mtune=native -flto"
CMAKE=(
-DBUILD_SHARED_LIBS:BOOL=TRUE
-DPACKAGE_LOCALE_DIR:PATH=/usr/share/locale
-DENABLE_BINRELOC:BOOL=FALSE
-DINKSCAPE_DATADIR:PATH=/usr/share
-DINKSCAPE_SHARE_INSTALL:PATH=/usr/share
-DLPE_ENABLE_TEST_EFFECTS:BOOL=FALSE
-DSHARE_INSTALL:PATH=/usr/share
-DWITH_ASAN:BOOL=FALSE
-DWITH_GNU_READLINE:BOOL=TRUE
-DWITH_GSOURCEVIEW:BOOL=FALSE
-DWITH_GSPELL:BOOL=TRUE
-DWITH_INTERNAL_2GEOM:BOOL=FALSE
-DWITH_INTERNAL_CAIRO:BOOL=FALSE
-DWITH_JEMALLOC:BOOL=FALSE
-DWITH_LPETOOL:BOOL=FALSE
-DWITH_MANPAGE_COMPRESSION:BOOL=TRUE
-DWITH_NLS:BOOL=TRUE
-DWITH_PROFILING:BOOL=FALSE
-DWITH_SVG2:BOOL=TRUE
-DWITH_X11:BOOL=TRUE
-DENABLE_POPPLER:BOOL=TRUE
-DENABLE_POPPLER_CAIRO:BOOL=TRUE
-DWITH_OPENMP:BOOL=TRUE
-DWITH_IMAGE_MAGICK:BOOL=FALSE
-DWITH_GRAPHICS_MAGICK:BOOL=TRUE
)
cmake ${CMAKE[@]} .
make -j$(nproc) VERBOSE=1
make clean
EOF
