#!/usr/bin/env bash

# adopted from https://zellij.dev/documentation/integration.html
ZJ_SESSIONS=$(zellij list-sessions)
NO_SESSIONS=$(echo "${ZJ_SESSIONS}" | wc -l)
# if ZJ_SESSIONS is empty, then set NO_SESSIONS to 0
if [ -z "${ZJ_SESSIONS}" ]; then
    NO_SESSIONS=0
fi

# check whether the string "(current)" is in ZJ_SESSIONS
if [[ "${ZJ_SESSIONS}" == *"(current)"* ]]; then
    # if so, then we are in a zellij session
    echo "already inside a session, existing."
else # ==> we are not in a zellij session
  if [ "${NO_SESSIONS}" -ge 1 ]; then  # sessions do exist
      ZJ_SESSIONS="$ZJ_SESSIONS\nnew_session\nkill_all_and_create_fresh_one"

      res="$(echo -e "${ZJ_SESSIONS}" | fzf)"

      if [ "${res}" = "new_session" ]; then
        zellij --layout st  # can't specify name here. I can call it "main" only if it is the first, otherwise name conflict! also, can't use attach -c syntax because layout can't be specified.
      elif [ "${res}" = "kill_all_and_create_fresh_one" ]; then
        zellij ka -y
        zellij --session main --layout st
      else
        zellij attach $res options --mirror-session false
      fi
  else  # no sessions, create one called main
     zellij --session main --layout st
  fi

fi
