#!/bin/bash
set -euo pipefail
lab_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
source "$lab_root/config/runtime.env"
lab_operation=${1:-baseline}
if [[ "$lab_operation" == build ]]; then
    exec sudo -n docker build --build-context "toolchain=$LAB_DATA_ROOT/dependencies" \
        --label "org.opencontainers.image.revision=1c971c4a36026f29acd0d8c52bed546bc742463c" \
        --label io.rtl9210b.lab=true -t "$LAB_IMAGE" "$lab_root"
fi
case "$lab_operation" in baseline|analyze|compare) ;; *) echo 'Operations: build, baseline, analyze, compare' >&2; exit 2 ;; esac
lab_mounts=()
lab_command=("$lab_operation")

exec sudo -n docker run --rm --network none --read-only --cap-drop ALL \
    --label io.rtl9210b.lab=true \
    --hostname "$LAB_HOSTNAME" --add-host "$LAB_HOSTNAME:127.0.0.1" \
    --security-opt no-new-privileges --user "$(id -u):$(id -g)" \
    --memory "$LAB_MEMORY" --cpus "$LAB_CPUS" --pids-limit "$LAB_PIDS" \
    --tmpfs /tmp:rw,nosuid,nodev,size=256m \
    --mount "type=bind,source=$LAB_DATA_ROOT/inputs,target=/inputs,readonly" \
    --mount "type=bind,source=$LAB_DATA_ROOT/current,target=/work/current" \
    --mount "type=bind,source=$lab_root/config,target=/opt/lab/config,readonly" \
    "${lab_mounts[@]}" "$LAB_IMAGE" "${lab_command[@]}"
