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

if [[ "${EUID}" -ne 0 ]]; then
  echo "Kjør som root: sudo bash $0"
  exit 1
fi

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

SRC_PS1="$REPO_ROOT/ps1/ps1.sh"
PS1_FILE="/etc/profile.d/ps1.sh"
BASH_BASHRC="/etc/bash.bashrc"

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

echo "Installerer global PS1: $SRC_PS1 -> $PS1_FILE"

cp -f "$SRC_PS1" "$PS1_FILE"
chmod 0644 "$PS1_FILE"

echo "Oppdaterer $BASH_BASHRC for å source $PS1_FILE (idempotent)"

# Remove old managed block if present, then add
tmp="$(mktemp)"
awk -v s="$MARKER_START" -v e="$MARKER_END" '
  $0==s {inside=1; next}
  $0==e {inside=0; next}
  !inside {print}
' "$BASH_BASHRC" > "$tmp"
cat "$tmp" > "$BASH_BASHRC"
rm -f "$tmp"

cat >> "$BASH_BASHRC" <<EOF2

$MARKER_START
# Load global PS1 (managed)
if [ -r "$PS1_FILE" ]; then
  . "$PS1_FILE"
fi
$MARKER_END
EOF2

echo "✅ Ferdig."
echo "Logg ut/inn (eller åpne ny shell) for å se global PS1."
echo
echo "Tips:"
echo "  - Tving NerdFont glyphs:  export PS1_FORCE_NF=1"
echo "  - Tving fallback:         export PS1_FORCE_ASCII=1"
