#!/bin/sh
# Regenerates the demo files of assets/demo (shop-0..4.cryo, shop.cryom, worker.cryf) with ext-cryo built from the PhpCryo
# sources:
#   (cd <a copy of ext-cryo> && phpize && ./configure --enable-cryo && make)
#   apps/cryo-studio/tools/demo/make_demo.sh <path of modules/cryo.so> [php binary, default /usr/bin/php]
# The worker runs in a temporary folder with an empty environment; the absolute folder is then rewritten "demo/" in the
# snapshots, so that no path of the machine is published.
# The freeze file worker.cryf is signed (HMAC of cryo.key, here "demo-key"): rewriting it would break the signature, so
# freeze_worker.php runs instead in a private mount and UTS namespace (unshare, no root needed) where the folder is
# /mnt/demo and the host name is cryo-demo: the file holds no path or name of the machine and stays signed.
set -e
SO="$1"
PHP="${2:-/usr/bin/php}"
[ -f "$SO" ] || { echo "usage: $0 <cryo.so> [php]" >&2; exit 2; }
APP="$(cd "$(dirname "$0")/../.." && pwd)"
WORK="$(mktemp -d)"
mkdir "$WORK/demo"
cp "$APP/assets/demo/shop_worker.php" "$WORK/demo/"
DIR="$(cd "$WORK/demo" && pwd -P)"
(cd "$DIR" && env -i PATH=/usr/bin:/bin "$PHP" -n -d extension="$SO" -d cryo.track_alloc=stack shop_worker.php)
for f in "$DIR"/shop-*.cryo; do
    "$PHP" -n "$APP/tools/demo/rewrite_paths.php" "$f" "$DIR/" "demo/"
done
cp "$DIR"/shop-*.cryo "$DIR"/shop.cryom "$APP/assets/demo/"
cp "$APP/assets/demo/freeze_worker.php" "$WORK/demo/"
cp "$SO" "$WORK/cryo.so"
unshare -r -u -m sh -c "hostname cryo-demo && mount --bind '$WORK' /mnt && cd /mnt/demo && \
    env -i PATH=/usr/bin:/bin '$PHP' -n -d extension=/mnt/cryo.so -d cryo.key=demo-key freeze_worker.php"
install -m 644 "$WORK/demo/worker.cryf" "$APP/assets/demo/worker.cryf"
rm -rf "$WORK"
LEAK="$( { cat "$APP"/assets/demo/shop-*.cryo "$APP"/assets/demo/shop.cryom
          "$PHP" -r 'echo gzuncompress(substr(file_get_contents($argv[1]), 16, -36));' "$APP/assets/demo/worker.cryf"; } \
        | grep -a -c -e "$WORK" -e "$HOME" -e "$(id -un)" || true)"
if [ "$LEAK" != "0" ]; then
    echo "a local path or name is still in assets/demo" >&2
    exit 1
fi
echo "assets/demo regenerated"
