#!/nix/store/4nmqxajzaf60yjribkgvj5j54x9yvr1r-bash-5.1-p12/bin/bash
set -e
mkdir -p -m 0755 "$root/etc" "$root/var/lib"
mkdir -p -m 0700 "$root/var/lib/private" "$root/root" /run/containers
if ! [ -e "$root/etc/os-release" ]; then
  touch "$root/etc/os-release"
fi

if ! [ -e "$root/etc/machine-id" ]; then
  touch "$root/etc/machine-id"
fi

mkdir -p -m 0755 \
  "/nix/var/nix/profiles/per-container/$INSTANCE" \
  "/nix/var/nix/gcroots/per-container/$INSTANCE"

cp --remove-destination /etc/resolv.conf "$root/etc/resolv.conf"

if [ "$PRIVATE_NETWORK" = 1 ]; then
  extraFlags+=" --private-network"
fi

if [ -n "$HOST_ADDRESS" ]  || [ -n "$LOCAL_ADDRESS" ] ||
   [ -n "$HOST_ADDRESS6" ] || [ -n "$LOCAL_ADDRESS6" ]; then
  extraFlags+=" --network-veth"
fi

if [ -n "$HOST_PORT" ]; then
  OIFS=$IFS
  IFS=","
  for i in $HOST_PORT
  do
      extraFlags+=" --port=$i"
  done
  IFS=$OIFS
fi

if [ -n "$HOST_BRIDGE" ]; then
  extraFlags+=" --network-bridge=$HOST_BRIDGE"
fi

extraFlags+=" "

for iface in $INTERFACES; do
  extraFlags+=" --network-interface=$iface"
done

for iface in $MACVLANS; do
  extraFlags+=" --network-macvlan=$iface"
done

# If the host is 64-bit and the container is 32-bit, add a
# --personality flag.
if [ "$(< ${SYSTEM_PATH:-/nix/var/nix/profiles/per-container/$INSTANCE/system}/system)" = i686-linux ]; then
  extraFlags+=" --personality=x86"
fi


# Run systemd-nspawn without startup notification (we'll
# wait for the container systemd to signal readiness)
# Kill signal handling means systemd-nspawn will pass a system-halt signal
# to the container systemd when it receives SIGTERM for container shutdown;
# containerInit and stage2 have to handle this as well.
exec /nix/store/24ljibki63lxk0m11qnw8fh9smh64g3x-systemd-249.7/bin/systemd-nspawn \
  --keep-unit \
  -M "$INSTANCE" -D "$root" $extraFlags \
  $EXTRA_NSPAWN_FLAGS \
  --notify-ready=yes \
  --kill-signal=SIGRTMIN+3 \
  --bind-ro=/nix/store \
  --bind-ro=/nix/var/nix/db \
  --bind-ro=/nix/var/nix/daemon-socket \
  --bind="/nix/var/nix/profiles/per-container/$INSTANCE:/nix/var/nix/profiles" \
  --bind="/nix/var/nix/gcroots/per-container/$INSTANCE:/nix/var/nix/gcroots" \
  --link-journal=try-guest \
  --setenv PRIVATE_NETWORK="$PRIVATE_NETWORK" \
  --setenv HOST_BRIDGE="$HOST_BRIDGE" \
  --setenv HOST_ADDRESS="$HOST_ADDRESS" \
  --setenv LOCAL_ADDRESS="$LOCAL_ADDRESS" \
  --setenv HOST_ADDRESS6="$HOST_ADDRESS6" \
  --setenv LOCAL_ADDRESS6="$LOCAL_ADDRESS6" \
  --setenv HOST_PORT="$HOST_PORT" \
  --setenv PATH="$PATH" \
   \
   \
   \
  /nix/store/431nfiisj26gjyprhjp30r83dvi9dmiq-container-init "${SYSTEM_PATH:-/nix/var/nix/profiles/system}/init"


