#!/bin/bash 
set -euo pipefail
IFS="$(printf '\n\t')"
ARG_1="${@:1}"
# Define if we should start projects
AUTORUN=true
if [[ "$ARG_1" = "false" || "$ARG_1" = "0" ]]; then
    AUTORUN=false
fi

#
# This script aims to be an entry point to tmux even for people without experience with linux
# It simplifies a bit the addition of commands or portability between projects.
#

# Public: name of the session used by all functions of this script
_session="`basename $PWD`"

# Public: Create the session and rename the default window attached by the first argument
#
# $1 - name of the first window of the session
#
function init_session() {
    tmux new -s "$_session" -d
    tmux rename-window -t "$_session":0 $1
}

# Public: send a command to the given window in script variable _session
#
# $1 - name of the window
# $2 - command to execute
# $3 - boolean defining if the command will be executed (default: true) or just waiting in prompt (false)
#
# Examples
#
# send_command "backend" "cd server"
# send_command "frontend" "PORT=8000 yarn develop" false
#
function send_command() {
    local name="$1"
    local command="$2"
    local fire="$3" # optional boolean
    local suffix=`[ "$fire" = true ] || [ "$fire" = "" ] && echo "C-m" || echo ""`
    tmux send-keys -t "$_session:$name" "$command" $suffix
}

# Public: open a new window in script variable _session
#
# $1 - name of the window
# $2 - command to execute
# $3 - working directory in which the new window is created
# $4 - boolean defining if the command will be executed (default: true) or just waiting in prompt (false)
#
# Examples
#
# open_window "backend" "PORT=3000 yarn start:dev" "./server"
# open_window "database" "docker compose up"
# open_window "ssh-prod" "ssh alias-production" . false
#
function open_window() {
    local name="$1"
    local command="$2"
    local directory="$3"
    local fire="$4" # optional boolean
    echo "Starting $name..."
    tmux new-window -t ${_session} -n $name
    if [ "$directory" != "" ] && [ `realpath "$directory"` != "$PWD" ]; then
        send_command $name "cd $directory" true
    fi
    if [ "$command" != "" ]; then
	send_command "$name" "$command" "$fire"
    fi
}

# >> EDIT FROM HERE <<

## Prepare environment with shared variables between windows
export NODE_ENV=development
if [[ -f ~/.nvm/nvm.sh ]];
then
  source ~/.nvm/nvm.sh
  nvm use 18
elif [[ "$(node -v)" != v18.* ]];
then
  echo "Node 18 is required"
  exit 1
fi

## Create session
default_window="root"
init_session $default_window

## Start a new window for each of your project commands, eg:
# open_window <WINDOW_NAME> <COMMAND> [DIRECTORY [EXECUTE_COMMAND=true]]
# send_command "backend" "yarn start" $AUTORUN

## Attach to newly created session
tmux attach -t "$_session:$default_window"
