still fixing this. nearly there.
[feisty_meow.git] / scripts / core / functions.sh
1 #!/bin/bash
2
3 # This defines some general, useful functions.
4
5 # test whether we've been here before or not.
6 skip_all=
7 function_sentinel &>/dev/null
8 if [ $? -eq 0 ]; then
9   # there was no error, so we can skip the inits.
10   if [ ! -z "$SHELL_DEBUG" ]; then
11     echo skipping functions.sh because already defined.
12   fi
13   skip_all=yes
14 fi
15
16 if [ -z "$skip_all" ]; then
17   if [ ! -z "$SHELL_DEBUG" ]; then
18     echo function definitions begin...
19   fi
20   
21   # a handy little method that can be used for date strings.  it was getting
22   # really tiresome how many different ways the script did the date formatting.
23   function date_stringer() {
24     local sep="$1"; shift
25     if [ -z "$sep" ]; then sep='_'; fi
26     date +"%Y$sep%m$sep%d$sep%H%M$sep%S" | tr -d '/\n/'
27   }
28   
29   # makes a directory of the name specified and then tries to change the
30   # current directory to that directory.
31   function mcd() {
32     if [ ! -d "$1" ]; then mkdir -p "$1"; fi
33     cd "$1"
34   }
35
36   # displays the value of a variable in bash friendly format.
37   function var() {
38     while true; do
39       local varname="$1"; shift
40       if [ -z "$varname" ]; then
41         break
42       fi
43       if [ -z "${!varname}" ]; then
44         echo "$varname undefined"
45       else
46         echo "$varname=${!varname}"
47       fi
48     done
49   }
50
51   function success_sound()
52   {
53     if [ ! -z "$CLAM_FINISH_SOUND" ]; then
54       bash $FEISTY_MEOW_SCRIPTS/multimedia/sound_play.sh "$CLAM_FINISH_SOUND"
55     fi
56   }
57
58   function error_sound()
59   {
60     if [ ! -z "$CLAM_ERROR_SOUND" ]; then
61       bash $FEISTY_MEOW_SCRIPTS/multimedia/sound_play.sh "$CLAM_ERROR_SOUND"
62     fi
63   }
64
65   # checks the result of the last command that was run, and if it failed,
66   # then this complains and exits from bash.  the function parameters are
67   # used as the message to print as a complaint.
68   function check_result()
69   {
70     if [ $? -ne 0 ]; then
71       echo -e "failed on: $*"
72       error_sound
73       exit 1
74     fi
75   }
76
77   # locates a process given a search pattern to match in the process list.
78   function psfind() {
79     local -a patterns=("${@}")
80     mkdir $TEST_TEMP/grid_logs &>/dev/null
81     local PID_DUMP="$(mktemp "$TMP/zz_pidlist.XXXXXX")"
82     local PIDS_SOUGHT=()
83     if [ "$OS" == "Windows_NT" ]; then
84       # needs to be a windows format filename for 'type' to work.
85       if [ ! -d c:/tmp ]; then
86         mkdir c:/tmp
87       fi
88       # windows7 magical mystery tour lets us create a file c:\\tmp_pids.txt, but then it's not really there
89       # in the root of drive c: when we look for it later.  hoping to fix that problem by using a subdir, which
90       # also might be magical thinking from windows perspective.
91       tmppid=c:\\tmp\\pids.txt
92       # we have abandoned all hope of relying on ps on windows.  instead
93       # we use wmic to get full command lines for processes.
94       # this does not exist on windows home edition.  we are hosed if that's
95       # what they insist on testing on.
96       wmic /locale:ms_409 PROCESS get processid,commandline </dev/null >"$tmppid"
97       local flag='/c'
98       if [ ! -z "$(uname -a | grep "^MING" )" ]; then
99         flag='//c'
100       fi
101       # we 'type' the file to get rid of the unicode result from wmic.
102       cmd $flag type "$tmppid" >$PID_DUMP
103       \rm "$tmppid"
104       local CR='
105 '  # embedded carriage return.
106       local appropriate_pattern="s/^.*  *\([0-9][0-9]*\)[ $CR]*\$/\1/p"
107       local -a PIDS_SOUGHT
108       for i in "${patterns[@]}"; do
109         PIDS_SOUGHT+=($(cat $PID_DUMP \
110           | grep -i "$i" \
111           | sed -n -e "$appropriate_pattern"))
112       done
113     else
114       /bin/ps $extra_flags wuax >$PID_DUMP
115       # pattern to use for peeling off the process numbers.
116       local appropriate_pattern='s/^[-a-zA-Z_0-9][-a-zA-Z_0-9]*  *\([0-9][0-9]*\).*$/\1/p'
117       # remove the first line of the file, search for the pattern the
118       # user wants to find, and just pluck the process ids out of the
119       # results.
120       local -a PIDS_SOUGHT
121       for i in "${patterns[@]}"; do
122         PIDS_SOUGHT+=($(cat $PID_DUMP \
123           | sed -e '1d' \
124           | grep -i "$i" \
125           | sed -n -e "$appropriate_pattern"))
126       done
127     fi
128     if [ ${#PIDS_SOUGHT[*]} -ne 0 ]; then echo ${PIDS_SOUGHT[*]}; fi
129     /bin/rm $PID_DUMP
130   }
131   
132   # finds all processes matching the pattern specified and shows their full
133   # process listing (whereas psfind just lists process ids).
134   function psa() {
135     if [ -z "$1" ]; then
136       echo "psa finds processes by pattern, but there was no pattern on the command line."
137       return 1
138     fi
139     p=$(psfind "$1")
140     if [ -z "$p" ]; then
141       # no matches.
142       return 0
143     fi
144     echo ""
145     echo "Processes containing \"$1\"..."
146     echo ""
147     if [ -n "$IS_DARWIN" ]; then
148       unset fuzil_sentinel
149       for i in $p; do
150         # only print the header the first time.
151         if [ -z "$fuzil_sentinel" ]; then
152           ps $i -w -u
153         else
154           ps $i -w -u | sed -e '1d'
155         fi
156         fuzil_sentinel=true
157       done
158     else 
159       # cases besides mac os x's darwin.
160       extra_flags=
161       if [ "$OS" = "Windows_NT" ]; then
162         # special case for windows.
163         extra_flags=-W
164         ps | head -1
165         for curr in $p; do
166           ps $extra_flags | grep "$curr" 
167         done
168       else
169         # normal OSes can handle a nice simple query.
170         ps wu $p
171       fi
172     fi
173   }
174   
175   # an unfortunately similarly named function to the above 'ps' as in process
176   # methods, but this 'ps' stands for postscript.  this takes a postscript file
177   # and converts it into pcl3 printer language and then ships it to the printer.
178   # this mostly makes sense for an environment where one's default printer is
179   # pcl.  if the input postscript causes ghostscript to bomb out, there has been
180   # some good success running ps2ps on the input file and using the cleaned
181   # postscript file for printing.
182   function ps2pcl2lpr() {
183     for $i in $*; do
184       gs -sDEVICE=pcl3 -sOutputFile=- -sPAPERSIZE=letter "$i" | lpr -l 
185     done
186   }
187   
188   function fix_alsa() {
189     sudo /etc/init.d/alsasound restart
190   }
191   
192   # switches from a /X/path form to an X:/ form.  this also processes cygwin paths.
193   function unix_to_dos_path() {
194     # we usually remove dos slashes in favor of forward slashes.
195     if [ ! -z "$SERIOUS_SLASH_TREATMENT" ]; then
196       # unless this flag is set, in which case we force dos slashes.
197       echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\/cygdrive//' | sed -e 's/\/\([a-zA-Z]\)\/\(.*\)/\1:\/\2/' | sed -e 's/\//\\/g'
198     else
199       echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\/cygdrive//' | sed -e 's/\/\([a-zA-Z]\)\/\(.*\)/\1:\/\2/'
200     fi
201   }
202   
203   # switches from an X:/ form to an /X/path form.
204   function dos_to_unix_path() {
205     # we always remove dos slashes in favor of forward slashes.
206     echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\([a-zA-Z]\):\/\(.*\)/\/\1\/\2/'
207   }
208
209   # returns a successful value (0) if this system is debian or ubuntu.
210   function debian_like() {
211     # decide if we think this is debian or ubuntu or a variant.
212     DEBIAN_LIKE=$(if [ ! -z "$(grep -i debian /etc/issue)" \
213         -o ! -z "$(grep -i ubuntu /etc/issue)" ]; then echo 1; else echo 0; fi)
214     if [ $DEBIAN_LIKE -eq 1 ]; then
215       # success; this is debianish.
216       return 0
217     else
218       # this seems like some other OS.
219       return 1
220     fi
221   }
222   
223   # su function: makes su perform a login.
224   # for some OSes, this transfers the X authority information to the new login.
225   function su() {
226     if debian_like; then
227       # debian currently requires the full version which imports X authority
228       # information for su.
229   
230       # get the x authority info for our current user.
231       source $FEISTY_MEOW_SCRIPTS/x_win/get_x_auth.sh
232   
233       if [ -z "$X_auth_info" ]; then
234         # if there's no authentication info to pass along, we just do a normal su.
235         /bin/su -l $*
236       else
237         # under X, we update the new login's authority info with the previous
238         # user's info.
239         (unset XAUTHORITY; /bin/su -l $* -c "$X_auth_info ; export DISPLAY=$DISPLAY ; bash")
240       fi
241     else
242       # non-debian supposedly doesn't need the extra overhead any more.
243       # or at least suse doesn't, which is the other one we've tested on.
244       /bin/su -l $*
245     fi
246   
247     # relabel the console after returning.
248     bash $FEISTY_MEOW_SCRIPTS/tty/label_terminal_with_infos.sh
249   }
250   
251   # sudo function wraps the normal sudo by ensuring we replace the terminal
252   # label if they're doing an su with the sudo.
253   function sudo() {
254     local first_command="$1"
255     /usr/bin/sudo "$@"
256     if [ "$first_command" == "su" ]; then
257       # yep, they were doing an su, but they're back now.
258       bash $FEISTY_MEOW_SCRIPTS/tty/label_terminal_with_infos.sh
259     fi
260   }
261   
262   # trashes the .#blah files that cvs and svn leave behind when finding conflicts.
263   # this kind of assumes you've already checked them for any salient facts.
264   function clean_cvs_junk() {
265     for i in $*; do
266       find $i -follow -type f -iname ".#*" -exec perl $FEISTY_MEOW_SCRIPTS/files/safedel.pl {} ";" 
267     done
268   }
269
270   # overlay for nechung binary so that we can complain less grossly about it when it's missing.
271   function nechung() {
272     local wheres_nechung=$(which nechung 2>/dev/null)
273     if [ -z "$wheres_nechung" ]; then
274       echo "The nechung oracle program cannot be found.  You may want to consider"
275       echo "rebuilding the feisty meow applications with this command:"
276       echo "bash $FEISTY_MEOW_SCRIPTS/generator/bootstrap_build.sh"
277     else
278       $wheres_nechung
279     fi
280   }
281   
282   # recreates all the generated files that the feisty meow scripts use.
283   function regenerate() {
284     bash $FEISTY_MEOW_SCRIPTS/core/bootstrap_shells.sh
285     echo
286     nechung
287   }
288
289   # generates a random password where the first parameter is the number of characters
290   # in the password (default 20) and the second parameter specifies whether to use
291   # special characters (1) or not (0).
292   # found function at http://legroom.net/2010/05/06/bash-random-password-generator
293   function random_password()
294   {
295     [ "$2" == "0" ] && CHAR="[:alnum:]" || CHAR="[:graph:]"
296     cat /dev/urandom | tr -cd "$CHAR" | head -c ${1:-32}
297     echo
298   }
299
300   # a wrapper for the which command that finds items on the path.  some OSes
301   # do not provide which, so we want to not be spewing errors when that
302   # happens.
303   function whichable()
304   {
305     to_find="$1"; shift
306     which which &>/dev/null
307     if [ $? -ne 0 ]; then
308       # there is no which command here.  we produce nothing due to this.
309       echo
310     fi
311     echo $(which $to_find)
312   }
313
314   # copies a set of custom scripts into the proper location for feisty meow
315   # to merge their functions and aliases with the standard set.
316   function recustomize()
317   {
318     user="$1"; shift
319     if [ -z "$user" ]; then
320       # use our default example user if there was no name provided.
321       user=fred
322     fi
323     if [ ! -d "$FEISTY_MEOW_DIR/customizing/$user" ]; then
324       echo "The customization folder provided for $user should be:"
325       echo "  '$FEISTY_MEOW_DIR/customizing/$user'"
326       echo "but that folder does not exist.  Skipping customization."
327       return 1
328     fi
329     regenerate >/dev/null
330     pushd "$FEISTY_MEOW_GENERATED/custom" &>/dev/null
331     local incongruous_files="$(bash "$FEISTY_MEOW_SCRIPTS/files/list_non_dupes.sh" "$FEISTY_MEOW_DIR/customizing/$user" "$FEISTY_MEOW_GENERATED/custom")"
332     if [ ${#incongruous_files} -ge 1 ]; then
333       echo "cleaning unknown older overrides..."
334       perl "$FEISTY_MEOW_SCRIPTS/files/safedel.pl" $incongruous_files
335       echo
336     fi
337     popd &>/dev/null
338     echo "copying custom overrides for $user"
339     mkdir "$FEISTY_MEOW_GENERATED/custom" 2>/dev/null
340     perl "$FEISTY_MEOW_SCRIPTS/text/cpdiff.pl" "$FEISTY_MEOW_DIR/customizing/$user" "$FEISTY_MEOW_GENERATED/custom"
341     regenerate
342   }
343
344   function add_cygwin_drive_mounts() {
345     for i in c d e f g h q z ; do
346       ln -s /cygdrive/$i $i
347     done
348   }
349
350
351   # takes a file to modify, and then it will replace any occurrences of the
352   # pattern provided as the second parameter with the text in the third
353   # parameter.
354   function replace_pattern_in_file()
355   {
356     local file="$1"; shift
357     local pattern="$1"; shift
358     local replacement="$1"; shift
359     if [ -z "$file" -o -z "$pattern" -o -z "$replacement" ]; then
360       echo "replace_pattern_in_file: needs a filename, a pattern to replace, and the"
361       echo "text to replace that pattern with."
362       return 1
363     fi
364     sed -i -e "s%$pattern%$replacement%g" "$file"
365   }
366
367   ##############
368
369   function function_sentinel() { return 0; }
370   
371   if [ ! -z "$SHELL_DEBUG" ]; then echo function definitions end....; fi
372   
373 fi
374