Allow ordering of profile scripts.
[profile.git] / .bash_profile
1 if tty -s || [ "${0:0:1}" = "-" -o "$1" = "force" ]; then
2   # Remember if nocaseglob was on.
3   shopt -q nocaseglob
4   nocg=$?
5   # Turn it off so we source stuff in the right order.
6   shopt -u nocaseglob
7
8   # Remember LC_ALL.
9   lc_all=$LC_ALL
10   # Turn it off to set case-sensitive matching
11   LC_ALL=C
12
13   # Force these to come before everything else.
14   required="OS.bashrc
15 PATH.bashrc
16 BECOME.bashrc"
17
18   # Remember PATH so we can mangle it to find tsort and sed.
19   path="$PATH"
20   PATH=/usr/bin:/bin:/usr/ccs/bin
21
22   # Sort all scripts by dependencies.
23   profile_d=${PROFILE_HOME:-~}/.profile.d
24   deps=
25   unsorted=
26   for i in $profile_d/*.bashrc; do
27     dep=$(sed -n 's/^##*[       ]*profile-required:[    ]*//p' "$i")
28     i="${i##$profile_d/}"
29     if [ -n "$dep" ]; then
30       for d in $dep; do
31         deps="$deps
32 $d $i"
33       done
34     else
35       unsorted="$unsorted
36 $i"
37     fi
38   done
39
40   deps="$deps$unsorted"
41
42   # Avoid odd number of tokens for tsort.
43   n=$(echo "$deps" | wc -w)
44   if [ $((n%2)) = 1 ]; then
45     deps="$deps
46 ${deps##*
47 }"
48   fi
49   deps=$(echo "$deps" | tsort)
50   deps="$required
51 $deps"
52
53   # Restore PATH.
54   PATH="$path"
55
56   # Source them all in the right order.
57   sourced=
58   for i in $deps; do
59     [ -e "$profile_d/$i" ] || continue
60     [ "${sourced/ $i /}" = "$sourced" ] || continue
61     . "$profile_d/$i"
62     sourced="$sourced $i "
63   done
64
65   # Maybe turn nocaseglob back on.
66   [ $nocg = 0 ] && shopt -s nocaseglob
67
68   # Reset LC_ALL.
69   LC_ALL=$lc_all
70
71   unset i d n dep deps profile_d path required unsorted sourced
72   unset lc_all nocg
73
74   # Don't inherit failure from the last script.
75   true
76 fi