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