#!/bin/bash
set -euo pipefail

# ───── Import des fonctions communes ─────
source /opt/scripts_remote/shared_functions.sh
MARKER_NAME="bash_aliases_configured"
TARGET_USER="dbi"
FORCE=false



# ───── Parse arguments ─────
for arg in "$@"; do
  [[ "$arg" == "--force" ]] && FORCE=true
done

# ───── Exécution conditionnelle en fonction du marqueur ─────
if read_setup_marker "$MARKER_NAME" && [[ "$FORCE" != true ]]; then
  echo "✅ bash_aliases déjà configuré — skipping."
  exit 0
fi

# Ensure user exists
if ! id "$TARGET_USER" &>/dev/null; then
    echo "❌ User '$TARGET_USER' does not exist. Skipping."
    exit 1
fi

# Get home directory
USER_HOME=$(getent passwd "$TARGET_USER" | cut -d: -f6)

if [ ! -d "$USER_HOME" ]; then
    echo "❌ Home directory $USER_HOME does not exist. Skipping."
    exit 1
fi

echo "🔧 Fixing .bash_aliases for user '$TARGET_USER'..."

# Remove incorrect sourcing from /etc/profile
if grep -q "/opt/.my_git_repos/denis_mbp/.bash_aliases" /etc/profile; then
    echo "🧹 Cleaning /etc/profile..."
    sudo sed -i '/source \/opt\/\.my_git_repos\/denis_mbp\/\.bash_aliases/d' /etc/profile
fi

# Remove incorrect sourcing from user's .bashrc
BASHRC="$USER_HOME/.bashrc"
if [ -f "$BASHRC" ]; then
    sed -i "/source .*\.my_git_repos\/denis_mbp\/\.bash_aliases/d" "$BASHRC"
fi

# Supprime le répertoire si --force est actif
REPO_DIR="$USER_HOME/ket-bash_aliases"
if [[ "$FORCE" == true && -d "$REPO_DIR" ]]; then
  echo "🧨 Suppression du répertoire existant $REPO_DIR (force)..."
  rm -rf "$REPO_DIR"
fi

# Clone le dépôt
echo "📥 Cloning repository ket-bash_aliases as $TARGET_USER..."
sudo -u "$TARGET_USER" /opt/scripts_remote/git/gitea_setup.sh --clone --repo-name ket-bash_aliases

# Write the new .bash_aliases
ALIASES_FILE="$USER_HOME/.bash_aliases"
cat > "$ALIASES_FILE" <<EOL
# ~/.bash_aliases (local)
source ~/ket-bash_aliases/.bash_aliases
# Optionnel : surcharge locale
[ -f ~/.bash_aliases_local ] && source ~/.bash_aliases_local
EOL

# Fix ownership
chown "$TARGET_USER:$TARGET_USER" "$ALIASES_FILE"

# ───── Crée le marqueur de setup une fois terminé ─────
create_setup_marker "$MARKER_NAME"

echo "✅ .bash_aliases for '$TARGET_USER' is configured. Marker saved at $MARKER_NAME"