#!/bin/sh

# Start with the base bwrap arguments in an array
bwrap_args=(
  --symlink usr/bin /bin
  --symlink usr/lib /lib
  --symlink usr/lib64 /lib64
  --ro-bind /usr /usr
  --proc /proc
  --dev /dev
  --tmpfs /tmp
  --dir /var
  --tmpfs /var/tmp
  --tmpfs "$HOME/rpmbuild"
  --unshare-all
  --share-net
  --die-with-parent
)

# Handle the system-wide config
if [[ -f "/etc/quilt.quiltrc" ]]; then
  bwrap_args+=(--dir /etc)
  bwrap_args+=(--ro-bind /etc/quilt.quiltrc /etc/quilt.quiltrc)
fi

# Handle the user-specific config
if [[ -f "$HOME/.quiltrc" ]]; then
  bwrap_args+=(--dir "$HOME")
  bwrap_args+=(--ro-bind "$HOME/.quiltrc" "$HOME/.quiltrc")
fi

# Add the writable current directory
bwrap_args+=(--dir "$PWD")
bwrap_args+=(--bind "$PWD" "$PWD")

# Check if we're in a source directory with a patches symlink and make that
# writeable as well
if [ "$(readlink patches)" = "../.." ]; then
  MAIN_SOURCE_DIR=$(realpath "$PWD/../../")
  bwrap_args+=(--dir "$MAIN_SOURCE_DIR")
  bwrap_args+=(--bind "$MAIN_SOURCE_DIR" "$MAIN_SOURCE_DIR")
fi

# The command to run
bwrap_args+=(/usr/bin/quilt "$@")

# Execute the final command
bwrap "${bwrap_args[@]}"

