#!/bin/bash
set -vex

REPOS=(${REPOS:=gitlab-profile core io integrate octree domain PM})
: ${SESSION_NAME:=hw}
: ${HW_BUILD=$PWD/build/}
: ${HW_DATA=$PWD/build/}

while getopts "cptlr:" opt
do
   case "$opt" in
      c ) clona=1 ;;
      t ) tmuxa=1 ;;
      r ) shift $(( OPTIND - 2 )) && REPOS=($@) && break
   esac
done

if [ -z "$clona" ] && [ -z "$tmuxa" ]; then
    echo 'usage: ./cloneall.bash -c (clone repos) -t (attach to tmux) -r (repos list, e.g. core io octree) '
    exit 1
fi

if [ ! -z "$clona" ]; then
    if [[ ! -f .env ]]; then
       echo "export HW_BUILD=$HW_BUILD" > .env
       echo "export HW_DATA=$HW_DATA" >> .env
       echo "export DEBUG=1" >> .env
    fi
    . .env
    for REPO in "${REPOS[@]}"; do

	[[ ! -d "$REPO" ]] && git clone ssh://git@git.ia2.inaf.it/hotwheels/$REPO.git
        pushd $REPO
	[[ ! -d "venv" ]] && python3 -mvenv venv && . venv/bin/activate && pip install autopep8  && pip install PyYaml
        git switch dev || echo no dev branch
        popd
    done
fi

if [ ! -z "$tmuxa" ]; then
    
    if ! tmux has-session -t $SESSION_NAME ; then
	# Create a new tmux session

	[[ -d full ]] && REPOS+=(full)
	
	for index in "${!REPOS[@]}"; do
            value="${REPOS[index]}"
	    
	    if [[ "$index" == 0 ]]; then
		tmux new-session -d -s $SESSION_NAME -c $PWD
	    else
		tmux new-window -t $SESSION_NAME -c $PWD
	    fi
            # Initialize the environment in the first window
            tmux send-keys -t $SESSION_NAME:$index ". .env" C-m
            tmux send-keys -t $SESSION_NAME:$index "cd $PWD/$value" C-m
            tmux send-keys -t $SESSION_NAME:$index ". venv/bin/activate" C-m
	    tmux rename-window $value
            
	done
    fi
    tmux attach-session -t $SESSION_NAME
fi

echo done
