#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

SRC_PS1="$REPO_ROOT/ps1/ps1.sh"
DST_DIR="$HOME/.config/ps1"
DST_PS1="$DST_DIR/ps1.sh"

MARKER_START="# >>> user ps1 (managed) >>>"
MARKER_END="# <<< user ps1 (managed) <<<"

mkdir -p "$DST_DIR"
cp -f "$SRC_PS1" "$DST_PS1"
chmod 0644 "$DST_PS1"

add_source_block() {
  local file="$1"
  [[ -f "$file" ]] || touch "$file"

  # remove old block
  local tmp
  tmp="$(mktemp)"
  awk -v s="$MARKER_START" -v e="$MARKER_END" '
    $0==s {inside=1; next}
    $0==e {inside=0; next}
    !inside {print}
  ' "$file" > "$tmp"
  cat "$tmp" > "$file"
  rm -f "$tmp"

  cat >> "$file" <<EOF

$MARKER_START
# Load user PS1 (managed)
if [ -r "$DST_PS1" ]; then
  . "$DST_PS1"
fi
$MARKER_END
EOF
}

# Bash on macOS may read .bash_profile for login shells; interactive shells read .bashrc
add_source_block "$HOME/.bashrc"
add_source_block "$HOME/.bash_profile"

echo "✅ macOS user PS1 installert:"
echo "   $DST_PS1"
echo "   sourcet fra ~/.bashrc og ~/.bash_profile"
echo
echo "Tips:"
echo "  - Tving NerdFont glyphs:  export PS1_FORCE_NF=1"
echo "  - Tving fallback:         export PS1_FORCE_ASCII=1"
echo "  - Disable:               export DISABLE_GLOBAL_PS1=1  eller touch ~/.config/ps1/disable"
