#!/bin/sh
# Rebuild the PS1 emulator and frontend shipped with LajkTo OS QA3 on x86-64 GNU/Linux.
# Usage: sh BUILD-PS1.sh /path/to/PCSX-ReARMed-LajkTo-source.tar.gz new-output-directory
# Requires GCC, GNU make, GNU binutils, git, coreutils and tar. No network access is needed.
# SPDX-License-Identifier: GPL-2.0-or-later
set -eu
if test "$#" -ne 2; then
    echo "Usage: sh BUILD-PS1.sh source-archive.tar.gz new-output-directory" >&2
    exit 2
fi
archive=$(realpath "$1")
out=$(realpath -m "$2")
test -f "$archive"
test ! -e "$out" || { echo "Choose a new output directory" >&2; exit 2; }
printf '%s  %s\n' '00d3240369c88cd223808b89b6d93cd15763680ec71acf1e854a5fcd5a99898c' "$archive" | sha256sum --check --status
work=$(mktemp -d)
trap 'rm -rf -- "$work"' EXIT
tar -xzf "$archive" -C "$work"
tar -xf "$work/upstream.tar" -C "$work"
cat > "$work/frontend/apps/consoles/build-archive.sh" <<'QA3_REBUILD'
#!/bin/sh
set -eu
# The caller supplies the pinned upstream tree and an output directory.
core=$(realpath "$1")
out=$(realpath -m "$2")
here=$(CDPATH= cd -- "$(dirname "$0")" && pwd)
rev=0f544ce1d18ac7dd114cb8f5507f01a29d3cd58c
test "$(git get-tar-commit-id < "$core/../upstream.tar")" = "$rev"
mkdir -p "$out"
export SOURCE_DATE_EPOCH=1795347668
export TZ=UTC
printf '#define REV "0f544ce"\n' > "$core/include/revision.h"
make -o include/revision.h -C "$core" -j4 -f Makefile.libretro GIT_VERSION='" 0f544ce"' platform=unix DYNAREC=0 BUILTIN_GPU=peops HAVE_CHD=0 HAVE_PHYSICAL_CDROM=0 USE_ASYNC_CDROM=0 USE_ASYNC_GPU=0 USE_ASYNC_SPU=0 NDRC_THREAD=0 USE_LIBRETRO_VFS=0
# Link using a basename dependency, independent of the build machine.
cc -O2 -Wall -Wextra -I"$core/deps/libretro-common/include" -I"$here/../../include" "$here/ps1.c" -L"$core" -Wl,-rpath,/home/emulators -l:pcsx_rearmed_libretro.so -o "$out/ps1"
cp "$core/pcsx_rearmed_libretro.so" "$out/"
strip --strip-unneeded "$out/ps1" "$out/pcsx_rearmed_libretro.so"

QA3_REBUILD
sh "$work/frontend/apps/consoles/build-archive.sh" "$work/pcsx" "$out"
(cd "$out" && sha256sum ps1 pcsx_rearmed_libretro.so)
