#!/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 ;;
      p ) pyinsta=1 ;;
      t ) tmuxa=1 ;;
      l ) linka=1 ;;
      r ) shift $(( OPTIND - 2 )) && REPOS=($@) && break
   esac
done

if [ -z "$clona" ] && [ -z "$pyinsta" ] && [ -z "$tmuxa" ] && [ -z "$linka" ];then
    echo 'usage: ./cloneall.bash -c (clone repos) -p (python install and tests) -t (attach to tmux) -l (full tree of links) -r (repos)'
    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
    [[ ! -d "venv" ]] && python3 -mvenv venv
    . venv/bin/activate
    pip install --upgrade pip
    pip install autopep8
    pip install matplotlib
    for REPO in "${REPOS[@]}"; do

	[[ ! -d "$REPO" ]] && git clone ssh://git@git.ia2.inaf.it/hotwheels/$REPO.git
        pushd $REPO
        git switch dev || echo no dev branch
	if [[ "$REPO" != "gitlab-profile" ]]; then
	    [ ! -z "$pyinsta" ] && python -mpip install -e .[edit] && python -m hotwheels.checkup hotwheels/
	fi
        popd
    done
fi

if [ ! -z "$linka" ]; then
    mkdir -p full/hotwheels
    touch full/hotwheels/__init__.py || echo cant touch
    for f in core/hotwheels/*; do
	[[ "${f##*/:0:2}" == "__" ]] && continue
	ln -sf $PWD/$f full/hotwheels/${f##*/}
    done
    for REPO in "${REPOS[@]}"; do
	if [ "$REPO" != "core" ] && [ "$REPO" != "gitlab-profile" ]; then
	    ln -sf $PWD/$REPO/hotwheels/$REPO full/hotwheels/$REPO
	fi
    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 ". venv/bin/activate" C-m
            tmux send-keys -t $SESSION_NAME:$index "cd $PWD/$value" C-m
	    tmux rename-window $value
            
	done
    fi
    tmux attach-session -t $SESSION_NAME
fi

echo done
