#!/bin/bash
#
#  THIS IS A CODE TO CREATE A WORKTREE FOR GIT BUT WITH SPARSE-CHECKOUT
#  THREE PARAMETERS:
#  1. Temporary Folder Where Edit will happen
#  2. Feature Name for the New Branch (must be unique)
#  3. PATH in git repo to display (relative path)
#

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

REJOIN_WORKTREE=0
CWD=`pwd`

# Folder where editting will take place
TempFolder="$1"
#  ~/11_opencode/p20260114_codetools_worktree

# Expand ~ and remove trailing slash for consistency
TempFolder="${TempFolder/#\~/$HOME}"
TempFolder="${TempFolder%/}"

# Name of the branch, name of the feature
FeatureName="$2"

# Folder inside git
GitSubFolder="$3"
#           dotfiles/codetools"

main_or_master1=`git symbolic-ref --short HEAD 2>/dev/null`

# Get the default branch name more reliably
main_or_master2=`git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@'`
if [ "$main_or_master2" = "" ]; then
    # Fallback: try common branch names
    for branch in main master develop; do
        if git rev-parse --verify "$branch" >/dev/null 2>&1; then
            main_or_master2="$branch"
            break
        fi
    done
fi

# Clean up any special characters from branch name (remove *, +, spaces)
main_or_master2=`echo "$main_or_master2" | sed 's/^[*+ ]*//' | sed 's/[ *+]$//'`

#echo "------------ master branch is named: " $main_or_master1
#echo "------------ master branch is named: " $main_or_master2

if [ "$main_or_master2" = "" ]; then
    main_or_master2=$main_or_master1
fi
echo -e "${BLUE}D...base  branch is named: ${NC}" $main_or_master2


if [ "$TempFolder" = "" ]; then
    echo -e "${RED}X... missing temporary edit folder (full path) - 1st parameter${NC}"
    exit 1
fi

if [ -d "$TempFolder"  ]; then
    echo -e "${GREEN}i... $TempFolder FOLDER exists${NC}"
    if [ -z "$(find "$TempFolder" -mindepth 1 -print -quit)" ]; then
	echo -e "${GREEN}i... fine, it is empty${NC}"
    else
	echo -e "${YELLOW}W... it is not empty... only rejoin is possible ...  ...${NC}"
	#exit 1
	REJOIN_WORKTREE=1
    fi
else
    echo -e "${YELLOW}W... $TempFolder doesnt exist... creating${NC}"
    mkdir -p "$TempFolder"
    #exit 1
    ls -dl "$TempFolder"
    echo ...
fi


if [ "$FeatureName" = "" ]; then
    echo -e "${RED}X... missing Feature Name to set new branch - 2nd parameter ${NC}"
    exit 1
fi



if [ "$GitSubFolder" = "" ]; then
    echo -e "${YELLOW}W... missing git subfolder (relative path) - 3rd parameter${NC}"
    echo -e "${YELLOW}W...                new - if you give par#3 ==  '.'   => all goes there ${NC}"
    echo -e "${YELLOW}W... REJOIN_WORKTREE mode only would be possible${NC}"
    echo -e "${CYAN}> Continue with REJOIN_WORKTREE mode? (y/N): ${NC}"
    read ans
    if [ "$ans" != "y" ] && [ "$ans" != "Y" ]; then
        echo -e "${RED}X... aborting${NC}"
        exit 1
    fi
    REJOIN_WORKTREE=1
elif  [ "$GitSubFolder" = "." ]; then
  echo -e "${CYAN}...  new option ... all project is in the worktree: ${NC}"
  echo -e "${CYAN}...  new option ... all project is in the worktree: ${NC}"
  echo -e "${CYAN}...  new option ... all project is in the worktree: ${NC}"
fi
# other possibility was EVERYTHING "."



echo -e "${BLUE}D... testing existing branches and worktrees ...${NC}"
git branch -l | grep "${FeatureName}" > /dev/null
if [ "$?" = "0" ];then
    echo -e "${YELLOW}W... THIS BRANCH ALREADY EXISTS: ${FeatureName}${NC}"
    git worktree list | grep "${FeatureName}" | grep "${TempFolder}"
    if [ "$?" = "0" ]; then
	echo -e "${YELLOW}W... THE WORKTREE in the folder EXISTS TOO${NC}"
	#echo .
	echo -e "${GREEN}i... I will continue with joining the existing worktree .... NEW_MODE${NC}"
	REJOIN_WORKTREE=1
    else
	echo -e "${RED}X... I quit... feature exists but tempfolder is different${NC}"
	git worktree list
	echo -e "${RED}X... I quit... feature exists but tempfolder is different${NC}"
	exit 1
    fi
fi


if [ "$REJOIN_WORKTREE" = "1" ]; then
    echo -e "${GREEN}i...  -------------- REJOINING WORKTREE ----------------------${NC}"
    echo -e "${GREEN}i... I go to  ${TempFolder} ...${NC}"
    cd "${TempFolder}"
    echo -e "${GREEN}i... I am in ${NC}`pwd`"
    if [ -z "$(git status --porcelain)" ]; then
	echo -e "${GREEN}i... git repo is clean${NC}"
    else
	# git commit -a -m "Closing feature  ${FeatureName} "
	echo -e "${RED}X... git repo is dirty... you need to comit in  ${TempFolder}${NC}"
	cd $CWD
	exit 1
    fi
    #----------- TO FINISH AND MERGE DO : -----------------------------"
    # ------------  entering the original git folder ---------------"
    echo i... going to "${CWD}"
    cd "${CWD}"
    echo i... checking out to "$main_or_master2"
    git checkout "$main_or_master2"
    echo "> Merge $FeatureName to $main_or_master2  ?: (ENTER)"
    read ans
    echo -e "${GREEN}i... merging${NC}"
    git merge "${FeatureName}"
    if [ "$?" = "0" ]; then
	#    -----------list worktrees ------------"
	git worktree list
	echo "> Remove Worktree in  ${TempFolder}  ?: (ENTER)"
	read ans
	echo -e "${GREEN}i... worktree remove${NC}"
	git worktree remove "${TempFolder}"
	git worktree list
	# i...   worktree should be removed.. but if it is stale...prune"
	# git worktree prune
	# ---------- list branches ----------and maby delete ---------"
	git branch -l
	echo "> Remove feature branch  $FeatureName ? : (ENTER)"
	read ans
	echo -e "${GREEN}i... removing branch${NC}"
	git branch -D "$FeatureName"
	echo "========================================= finished ========="
	git branch -l
	echo -e "${GREEN}i... ALL DONE AND CLEANED${NC}"
    else
	echo -e "${RED}X... merge failed${NC}"
	echo -e "${YELLOW}Suggestion: run 'git mergetool' to resolve conflicts${NC}"
	echo -e "${YELLOW}Then manually clean up with:${NC}"
	echo -e "${CYAN}  git worktree remove ${TempFolder}${NC}"
	echo -e "${CYAN}  git branch -D ${FeatureName}${NC}"
	exit 1
    fi

     exit 0
fi

# ===========   CREATING WORKTREE

echo -e "${GREEN}i... existing worktrees and  branches :  ---------------${NC}"
git worktree list;
if [ "$?" != "0" ]; then
    echo -e "${RED}X... some error.... I quit (maybe no GIT  repo )${NC}"
    exit 1
fi
git branch -l
if [ "$?" != "0" ]; then
    echo -e "${RED}X... some error.... I quit (maybe no GIT  repo )${NC}"
    exit 1
fi
echo ">  press ENTER to create a worktree with the feature :: $FeatureName :: "
read ans


#exit 1

#============================= end both versions of WORKTREE ==============
# CREATE WORKTREE  .
if [ "${GitSubFolder}" = "." ]; then
    echo   echo -e "${CYAN}...  new option ... all project is in the worktree: ${NC}"
    echo   echo -e "${CYAN}...  I JUST LEAVE sparse-checkout commented  ${NC}"

    echo -e "${GREEN}i... CREATING A WORKTREE with branch  ${FeatureName} ${NC}"
    git worktree add  -b "${FeatureName}"  "${TempFolder}"
    if [ "$?" != "0" ]; then
	echo -e "${RED}X... some error.... I quit (maybe no commit yet)${NC}"
	exit 1
    fi

    echo -e "${CYAN} ------------  entering temp-work folder to check ---------------${NC}"
    cd  "${TempFolder}"
    if [ "$?" != "0" ]; then
	echo -e "${RED}X... some error.... I quit${NC}"
	exit 1
    fi

else
# CREATE WORKTREE  subtree

echo -e "${GREEN}i... CREATING A WORKTREE with branch  ${FeatureName} ${NC}"
git worktree add --no-checkout -b "${FeatureName}"  "${TempFolder}"
if [ "$?" != "0" ]; then
    echo -e "${RED}X... some error.... I quit (maybe no commit yet)${NC}"
    exit 1
fi


echo -e "${CYAN} ------------  entering temp-work folder to check ---------------${NC}"
cd  "${TempFolder}"
if [ "$?" != "0" ]; then
    echo -e "${RED}X... some error.... I quit${NC}"
    exit 1
fi

git sparse-checkout init --cone
if [ "$?" != "0" ]; then
    echo -e "${RED}X... some error.... I quit${NC}"
    exit 1
fi

### echo .... D... git subfolder ...: "${GitSubFolder}"
git sparse-checkout set  "${GitSubFolder}"
if [ "$?" != "0" ]; then
    echo -e "${RED}X... some error.... I quit${NC}"
    exit 1
fi
git sparse-checkout list
if [ "$?" != "0" ]; then
    echo -e "${RED}X... some error.... I quit${NC}"
    exit 1
fi

#============================= end both versions of WORKTREE ==============
fi
#============================= end both versions of WORKTREE ==============



echo -e "${GREEN}i...  It Will Complain Now 'already on ... ' ... IDK${NC}"
git checkout "${FeatureName}" # not sure, but it worked
if [ "$?" != "0" ]; then
    echo -e "${RED}X... some error.... I quit${NC}"
    exit 1
fi


echo .
echo .
echo .
echo -e "${GREEN}===================   ALL IS PREPARED ================================${NC}"
# echo .
# echo .
# echo "#----------- TO FINISH AND MERGE DO : -----------------------------"
# echo  git commit -a -m "Closing feature  ${FeatureName} "
# echo "# ------------  entering the original git folder ---------------"
# echo  cd "${CWD}"
# echo  git checkout "$main_or_master2"
# echo  git merge "${FeatureName}"
# echo "-----------list worktrees ------------"
# echo  git worktree list
# echo  git worktree remove "${TempFolder}"
# echo  git worktree list
# echo "# i...   worktree should be removed.. but if it is stale...prune"
# echo  "# git worktree prune"
# echo "# ---------- list branches ----------and maby delete ---------"
# echo "git branch -l"
# echo "# git branch -D $FeatureName"
# echo "# git branch -l"


echo ".. Q ..  in a case of dangling branch ..............."
echo ".. Q ..  git branch -d rm"
echo ".. Q .. ..... if not working and worktree is active"
echo ".. Q ..  git worktree prune"
echo ".. Q ..  git branch -D rm"
echo ".. Q ..  git branch -l"
echo ".. Q .. "
echo ".. Q .. "
