#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-or-later

set -eu

script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
source_dir=$(CDPATH= cd -- "$script_dir/.." && pwd)
prefix=${A6_RECOVERY_PREFIX:-"$source_dir/build/limd-prefix"}
endpoint=${QEMU_USB_ENDPOINT:-127.0.0.1:26050}
lab_dir=${A6_LAB_DIR:-}
binary="$prefix/bin/idevicerestore"

if [ ! -x "$binary" ]; then
    echo "QEMU-enabled idevicerestore not found: $binary" >&2
    echo "Run scripts/build-macos-recovery-tools.sh first." >&2
    exit 1
fi

export LIBIRECOVERY_QEMU=$endpoint
export DYLD_LIBRARY_PATH="$prefix/lib${DYLD_LIBRARY_PATH:+:$DYLD_LIBRARY_PATH}"
if [ -n "$lab_dir" ]; then
    lab_dir=$(CDPATH= cd -- "$lab_dir" && pwd)
    for image in iBSS.chain-encrypted.dfu iBEC.chain-nonce-encrypted.dfu; do
        if [ ! -f "$lab_dir/$image" ]; then
            echo "Lab image not found: $lab_dir/$image" >&2
            exit 1
        fi
    done
    export IDEVICERESTORE_QEMU_LAB_DIR=$lab_dir
    export IDEVICERESTORE_QEMU_LAB_BOOT_ONLY=1
    exec "$binary" -z "$@"
fi
exec "$binary" "$@"
