# shellcheck shell=sh

# shellcheck disable=SC2250

add_paths() {
  var=$1
  shift
  dirs=$1
  shift
  new=:
  saved_ifs=$IFS
  IFS=:
  for prefix; do
    for dir in $dirs; do
      [ -d "$prefix/$dir" ] && new=$new$prefix/$dir:
    done
  done
  eval "old=\$$var"
  # shellcheck disable=SC2154
  for dir in $old; do
    case $new in
      *:$dir:*) ;;
      *) new=$new$dir: ;;
    esac
  done
  IFS=$saved_ifs
  new=${new#:}
  new=${new%:}
  eval "export $var=\$new"
  unset var dirs new saved_ifs prefix dir old
}

add_paths PATH bin:sbin ~/.local ~/.cargo ~/.go ~/.bun /opt/homebrew
add_paths CPATH include ~/.local /opt/homebrew
add_paths LIBRARY_PATH lib ~/.local /opt/homebrew


unset -f add_paths
