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