#/bin/bash

project_dir=$( pwd )

bubblewrap=$( command -v bwrap )
agents=(
  $( command -v claude )
  $( command -v pi )
  $( command -v ps ) # for testing
)

if [[ "${project_dir}" = "${HOME}" ]]; then
     echo "Not running in ${HOME}"
     exit
fi

if [[ -n "${1}" ]] && [[ -n $( command -v "${1}" ) ]]; then
	coder=$( command -v "${1}" ) && shift
        args="${@}"
else
	echo "Please specify a coding agent"
	exit
fi

if ! [[ " ${agents[@]} " =~ " ${coder} " ]]; then
	echo "No agent found"
	exit
fi

declare -a ro_binds
declare -a binds

ro_binds=(
  /usr
  /lib
  /lib64
  /bin
  /etc/resolv.conf
  /etc/hosts
  /etc/ssl
  /etc/passwd
  /etc/group
)

for loc in "${HOME}/.gitconfig" "${HOME}/.local"; do
  if [[ -e "${loc}" ]]; then
    ro_binds+=("${loc}")
  fi
done

binds=()

for loc in "${HOME}/.claude" "${HOME}/.pi" "${project_dir}"; do
  if [[ -e "${loc}" ]]; then
    binds+=("${loc}")
  fi
done

for i in "${!ro_binds[@]}"; do
  ro_binds["${i}"]="--ro-bind ${ro_binds[${i}]} ${ro_binds[${i}]}"
done
for i in "${!binds[@]}"; do
  binds["${i}"]="--bind ${binds[${i}]} ${binds[${i}]}"
done

${bubblewrap} \
     ${ro_binds[@]} \
     ${binds[@]} \
     --tmpfs /tmp \
     --proc /proc \
     --dev /dev \
     --share-net \
     --unshare-pid \
     --die-with-parent \
     --chdir "${project_dir}" \
     "$( command -v ${coder} )" "${args}"
