#!/bin/bash

if [[ -z "${WELCOME_SCRIPT_PATH}" ]]; then
  WELCOME_SCRIPT_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." &>/dev/null && pwd)"
fi

#region INCLUDES
. "${WELCOME_SCRIPT_PATH}/config/config_git.sh"
#endregion

getbranch(){
    local branch

    # Récupère le nom de la branche actuelle
    branch=$(git branch --show-current 2>/dev/null)
    if [[ -z "$branch" ]]; then
      msg_error "Pas dans un dépôt Git"
      exit
    fi

    echo "$branch"
}

gitinit(){

  local git_user git_email repo_name fold_name

  # prepare vars
  git_user="${1:-$CONFIG_GIT_USER}"
  git_email="${2:-$CONFIG_GIT_EMAIL}"
  fold_name=$(basename "$(pwd)")
  repo_name="${3:-$CONFIG_GIT_SERVER}${git_user}/${fold_name}.git"

  msg_info "Set git user : ${git_user} ${git_email}"
  git config --global --replace-all user.name "${git_user}"
  git config --global --replace-all user.email "${git_email}"

  echo "
# Ignorer les phpstorm
.idea

# Ignorer les backups et fichiers temporaires
*~
*.bak
*.swp
*.save" > .gitignore
  echo "" > LICENSE
  echo "" > CHANGELOG.md
  echo "" > README.md

  msg_info "Init git repository"
  git init
  git add .
  git commit -m "Initial commit"
  git branch -M main

  msg_info "Adding origin : ${repo_name}"
  git remote add origin "${repo_name}"

  msg_info "Try to create repository on git server...
  curl -X POST \"${CONFIG_GIT_SERVER}api/v1/user/repos\" \\
       -H \"accept: application/json\" \\
       -H \"Authorization: token ${CONFIG_GIT_TOKEN_INIT}\" \\
       -H \"Content-Type: application/json\" \\
       -d \"{\\\"name\\\":\\\"${fold_name}\\\", \\\"private\\\":true}\""

  # Create repo on git server
  if ! curl -f -s -X POST "${CONFIG_GIT_SERVER}api/v1/user/repos" \
     -H "accept: application/json" \
     -H "Authorization: token ${CONFIG_GIT_TOKEN_INIT}" \
     -H "Content-Type: application/json" \
     -d "{\"name\":\"${fold_name}\", \"private\":true}"; then

    msg_error "Error while creating new repository on ${CONFIG_GIT_SERVER}"
    return 1
  fi

  # Push repo on git server
  if ! git push -u origin main --force; then
    msg_error "Error while pushing to ${repo_name}"
    return 2
  fi
}

gitreset(){
  local branch
  branch=$(getbranch)

  git fetch origin
  git reset --hard origin/"${1:-$branch}"
  git clean -fd

 msg_success "Dépôt synchronisé et nettoyé."
}

gitsync(){
  local branch
  branch=$(getbranch)

  git fetch
  git pull origin "${1:-$branch}"
}

gitclone(){

  if [[ -z "$1" ]]; then
    msg_warning "Veuillez préciser l'adresse d'un dépôt Git"
    return 1
  fi

  git init
  git remote add origin "$1"
  git fetch
  git reset --hard origin/main
  git clean -fd

  msg_success "Dépôt cloné."
}

giturl(){
  local branch
  branch=$(getbranch)

  git remote set-url origin "$1"

  msg_success "Url du dépôt changé en $1."
}

gitssl() {
  local choice="${1:-true}"
  git config --global http.sslVerify "$choice"
}


gitversion(){

  local version

  # --- RÉCUPÉRATION DYNAMIQUE DE LA version ---
  # On récupère le dernier tag existant.
  # Si aucune erreur, on le stocke. Sinon, on part de 1.0.0 par défaut.
  version=$(git describe --tags --abbrev=0 2>/dev/null)

  if [ -z "$version" ]; then
      version="1.0.0"
      msg_warning "Aucun tag trouvé, initialisation à la version $version"
  else
      msg_info "Version actuelle détectée : $version"
  fi

  # --- SAISIE DU MESSAGE ---
  read -p "Commit message for version $version: " msg

  # Message par défaut si vide
  msg=${msg:-"Release version $version"}

  # --- OPÉRATIONS GIT ---

  # On s'assure d'être à jour
  msg_info "Synchronisation locale...🔄"
  git pull --rebase

  # Ajout et commit
  git add .

  # On vérifie s'il y a quelque chose à commiter pour éviter l'erreur
  if git diff-index --quiet HEAD --; then
      msg_info "Rien à commiter, passage direct aux tags."
  else
      git commit -m "$msg"
      git push
  fi

  # --- GESTION DES TAGS ---
  msg_info "Mise à jour du tag $version..."

  # Supprimer le tag localement
  git tag -d "$version" 2>/dev/null

  # Supprimer le tag distant (syntaxe moderne)
  git push origin --delete "$version" 2>/dev/null

  # Créer le nouveau tag annoté
  git tag -a "$version" -m "version $version"

  # Pousser le tag
  git push origin "$version"

  msg_success " Terminé ! La version $version est à jour."
}

script_update() {
  local BRANCH LOCAL REMOTE current_path

  current_path="$PWD"

  cd "$WELCOME_SCRIPT_PATH" || return 2

  if ! git fetch origin >/dev/null 2>&1; then
    msg_error "Erreur lors du Fetch"
    cd "$current_path" || :
    return 3
  fi

  BRANCH=$(git rev-parse --abbrev-ref HEAD)
  LOCAL=$(git rev-parse HEAD)
  REMOTE=$(git rev-parse origin/"$BRANCH")

  if [ "$LOCAL" = "$REMOTE" ] && git diff --quiet && git diff --cached --quiet; then
    cd "$current_path" || :
    return 0
  fi

  # update
  echo ""

  if git reset --hard origin/"$BRANCH"; then
    msg_success "Les script de welcome a été mis à jour !! relancer le ssh pour profiter des nouvelles fonctionnalités"
    echo ""
    cd "$current_path" || :
    return 1
  else
    msg_error "Erreur lors de la mise à jour du script"
    cd "$current_path" || :
    return 4
  fi
}