#!/bin/sh
# Boot the lab: initialise a clean Wine prefix pinned to a legacy code page
# (CP1252) and lay out the confined working directory + out-of-tree target area.
#
# This does NOT run the exploit. It only prepares the runtime so the exploiter
# and verifier can drive `xz.exe` under Wine.
set -eu

export WINEPREFIX="${WINEPREFIX:-/root/.wine}"
export WINEARCH="${WINEARCH:-win64}"
export WINEDEBUG="${WINEDEBUG:--all}"
WINE_INIT_LOCALE="${WINE_INIT_LOCALE:-en_US.CP1252}"

# Initialise the Wine prefix once (idempotent). The prefix is booted under the
# CP1252 locale so Wine bakes ACP=1252 into the prefix registry -> the legacy
# best-fit mapping is in force for every subsequent launch, regardless of the
# runtime launch locale.
if [ ! -f "${WINEPREFIX}/system.reg" ]; then
    echo ">>> initialising Wine prefix at ${WINEPREFIX} under ${WINE_INIT_LOCALE} (runs once)"
    LANG="${WINE_INIT_LOCALE}" LC_ALL="${WINE_INIT_LOCALE}" wineboot --init >/dev/null 2>&1 || true
    LANG="${WINE_INIT_LOCALE}" LC_ALL="${WINE_INIT_LOCALE}" wineserver -w || true
fi

# Confirm the legacy code page is actually pinned (best-fit precondition).
ACP="$(wine reg query 'HKLM\System\CurrentControlSet\Control\Nls\CodePage' /v ACP 2>/dev/null | awk '/ACP/{print $NF}')"
echo ">>> Wine ACP (legacy code page) = ${ACP:-unknown} (expect 1252)"

# ---------------------------------------------------------------------------
# Directory layout realising the criterion's confinement baseline.
#
#   /lab/work    -> CONFINED working directory. xz is launched from here.
#                   A file dropped here under its literal name is in-tree.
#   /lab/outside -> OUT-OF-TREE target area, a SIBLING of the confined dir.
#                   Reachable from /lab/work only via a "../" traversal, which
#                   the literal Unicode argument cannot express -- only the
#                   best-fit rewrite of U+2215 -> '/' can.
#
# We establish a clean baseline: the outside area exists and is empty, so any
# file that later appears there is unambiguously the result of the traversal.
# ---------------------------------------------------------------------------
mkdir -p /lab/work /lab/outside
# Establish/refresh a known-clean baseline of the out-of-tree target area on
# every boot, so post-run mutation is unambiguous.
rm -rf /lab/outside/*
find /lab/outside -mindepth 1 -maxdepth 1 -exec rm -rf {} + 2>/dev/null || true

echo ">>> lab ready: confined dir /lab/work ; out-of-tree target /lab/outside"
echo ">>> vulnerable xz : /opt/xz-vuln/bin/xz.exe"
echo ">>> patched   xz : /opt/xz-patched/bin/xz.exe"

exec "$@"
