i3 &
i3_pid="$!"

# TODO: We still get the error:
#   i3: Could not mkdir(/run/user/1000/i3): File exists
#   i3: Check permissions of $XDG_RUNTIME_DIR = '/run/user/1000'
# sometimes. Look into it. Might be fixed in new version? We often shut down
# with a manual `systemctl poweroff` from within i3 (i.e. while it's still
# running), might that be the problem?

# Spinlock until `i3` has initialized the IPC socket and set the
# `I3_SOCKET_PATH` property of the X11 root window that other xsession programs
# might require. If `i3` fails for some reason, retrieve its exit code and exit
# ourselves with it.
# <https://i3wm.org/docs/ipc.html>
while ! i3 --get-socketpath > '/dev/null'
do
  # TODO: If the last started background job (`%%`, i.e. `i3 &`) exited (`!
  # jobs %%`) we want to get its exit status (`wait %%`). This seems to not be
  # the way to do it though, since in the case where the job did exit, the
  # `wait %%` gives "wait: No current job". Do some research, it must be
  # possible to get the exit status of the last started job. Would it work to
  # just use `$i3_pid` instead of `%%`?
  if ! jobs %% > '/dev/null' 2>&1
  then
    wait %%
    exit $?
  fi
done

# while ! i3 --get-socketpath > '/dev/null'
# do
#   if ! kill -0 "$i3_pid" > '/dev/null' 2>&1
#   then
#     wait "$i3_pid"
#     exit $?
#   fi
# done

# while ! [ -e "${XDG_RUNTIME_DIR:-"/run/user/$(id -u)"}/i3/ipc-socket.$i3_pid" ]
# do
#   if ! [ "$(ps -p "$i3_pid" -o pid=)" ]
#   then
#     wait "$i3_pid"
#     exit $?
#   fi
# done
