0d1be4af851bc38239a1c9c672f6ecfe7b43893d
[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   # sets the variable in parameter 1 to the value in parameter 2, but only if
82   # that variable was undefined.
83   function set_var_if_undefined()
84   {
85     local var_name="$1"; shift
86     local var_value="$1"; shift
87     if [ -z "${!var_name}" ]; then
88       eval export $var_name="$var_value"
89     fi
90   }
91
92   function success_sound()
93   {
94     if [ ! -z "$CLAM_FINISH_SOUND" ]; then
95       bash $FEISTY_MEOW_SCRIPTS/multimedia/sound_play.sh "$CLAM_FINISH_SOUND"
96     fi
97   }
98
99   function error_sound()
100   {
101     if [ ! -z "$CLAM_ERROR_SOUND" ]; then
102       bash $FEISTY_MEOW_SCRIPTS/multimedia/sound_play.sh "$CLAM_ERROR_SOUND"
103     fi
104   }
105
106   # checks the result of the last command that was run, and if that failed,
107   # then this complains and exits from bash.  the function parameters are
108   # used as the message to print as a complaint.
109   function check_result()
110   {
111     if [ $? -ne 0 ]; then
112       echo -e "failed on: $*"
113       error_sound
114       exit 1
115     fi
116   }
117
118   # locates a process given a search pattern to match in the process list.
119   # supports a single command line flag style parameter of "-u USERNAME";
120   # if the -u flag is found, a username is expected afterwards, and only the
121   # processes of that user are considered.
122   function psfind() {
123     local -a patterns=("${@}")
124 #echo ====
125 #echo patterns list is: "${patterns[@]}"
126 #echo ====
127
128     local user_flag
129     if [ "${patterns[0]}" == "-u" ]; then
130       user_flag="-u ${patterns[1]}" 
131 #echo "found a -u parm and user=${patterns[1]}" 
132       # void the two elements with that user flag so we don't use them as patterns.
133       unset patterns[0] patterns[1]=
134     else
135       # select all users.
136       user_flag="-e"
137     fi
138
139     local PID_DUMP="$(mktemp "$TMP/zz_pidlist.XXXXXX")"
140     local -a PIDS_SOUGHT
141
142     if [ "$OS" == "Windows_NT" ]; then
143       # gets cygwin's (god awful) ps to show windoze processes also.
144       local EXTRA_DOZER_FLAGS="-W"
145       # pattern to use for peeling off the process numbers.
146       local pid_finder_pattern='s/ *\([0-9][0-9]*\) *.*$/\1/p'
147
148     else
149       # flags which clean up the output on unixes, which apparently cygwin
150       # doesn't count as.  their crappy specialized ps doesn't support this.
151       local EXTRA_UNIX_FLAGS="-o pid,args"
152       # pattern to use for peeling off the process numbers.
153       local pid_finder_pattern='s/^[[:space:]]*\([0-9][0-9]*\).*$/\1/p'
154     fi
155
156     /bin/ps $EXTRA_DOZER_FLAGS $EXTRA_UNIX_FLAGS $user_flag | tail -n +2 >$PID_DUMP
157 #echo ====
158 #echo got all this stuff in the pid dump file:
159 #cat $PID_DUMP
160 #echo ====
161
162     # search for the pattern the user wants to find, and just pluck the process
163     # ids out of the results.
164     local i
165     for i in "${patterns[@]}"; do
166       PIDS_SOUGHT+=($(cat $PID_DUMP \
167         | grep -i "$i" \
168         | sed -n -e "$pid_finder_pattern"))
169     done
170 #echo ====
171 #echo pids sought list became:
172 #echo "${PIDS_SOUGHT[@]}"
173 #echo ====
174
175     if [ ${#PIDS_SOUGHT[*]} -ne 0 ]; then
176       local PIDS_SOUGHT2=$(printf -- '%s\n' ${PIDS_SOUGHT[@]} | sort | uniq)
177       PIDS_SOUGHT=()
178       PIDS_SOUGHT=${PIDS_SOUGHT2[*]}
179       echo ${PIDS_SOUGHT[*]}
180     fi
181     /bin/rm $PID_DUMP
182   }
183   
184   # finds all processes matching the pattern specified and shows their full
185   # process listing (whereas psfind just lists process ids).
186   function psa() {
187     if [ -z "$1" ]; then
188       echo "psa finds processes by pattern, but there was no pattern on the command line."
189       return 1
190     fi
191     local -a patterns=("${@}")
192     p=$(psfind "${patterns[@]}")
193     if [ -z "$p" ]; then
194       # no matches.
195       return 0
196     fi
197
198     if [ "${patterns[0]}" == "-u" ]; then
199       # void the two elements with that user flag so we don't use them as patterns.
200       unset patterns[0] patterns[1]=
201     fi
202
203     echo ""
204     echo "Processes matching ${patterns[@]}..."
205     echo ""
206     if [ -n "$IS_DARWIN" ]; then
207       unset fuzil_sentinel
208       for i in $p; do
209         # only print the header the first time.
210         if [ -z "$fuzil_sentinel" ]; then
211           ps $i -w -u
212         else
213           ps $i -w -u | sed -e '1d'
214         fi
215         fuzil_sentinel=true
216       done
217     else 
218       # cases besides mac os x's darwin.
219       if [ "$OS" == "Windows_NT" ]; then
220         # special case for windows.
221         ps | head -1
222         for curr in $p; do
223           ps -W -p $curr | tail -n +2
224         done
225       else
226         # normal OSes can handle a nice simple query.
227         ps wu $p
228       fi
229     fi
230   }
231   
232   # an unfortunately similarly named function to the above 'ps' as in process
233   # methods, but this 'ps' stands for postscript.  this takes a postscript file
234   # and converts it into pcl3 printer language and then ships it to the printer.
235   # this mostly makes sense for an environment where one's default printer is
236   # pcl.  if the input postscript causes ghostscript to bomb out, there has been
237   # some good success running ps2ps on the input file and using the cleaned
238   # postscript file for printing.
239   function ps2pcl2lpr() {
240     for $i in $*; do
241       gs -sDEVICE=pcl3 -sOutputFile=- -sPAPERSIZE=letter "$i" | lpr -l 
242     done
243   }
244   
245   function fix_alsa() {
246     sudo /etc/init.d/alsasound restart
247   }
248   
249   # switches from a /X/path form to an X:/ form.  this also processes cygwin paths.
250   function unix_to_dos_path() {
251     # we usually remove dos slashes in favor of forward slashes.
252     local DOSSYHOME
253     if [[ ! "$OS" =~ ^[Ww][iI][nN] ]]; then
254       # fake this value for non-windows (non-cygwin) platforms.
255       DOSSYHOME="$HOME"
256     else
257       # for cygwin, we must replace the /home/X path with an absolute one, since cygwin
258       # insists on the /home form instead of /c/cygwin/home being possible.  this is
259       # super frustrating and nightmarish.
260       DOSSYHOME="$(cygpath -am "$HOME")"
261     fi
262
263     if [ ! -z "$SERIOUS_SLASH_TREATMENT" ]; then
264       # unless this flag is set, in which case we force dos slashes.
265       echo "$1" | sed -e "s?^$HOME?$DOSSYHOME?g" | sed -e 's/\\/\//g' | sed -e 's/\/cygdrive//' | sed -e 's/\/\([a-zA-Z]\)\/\(.*\)/\1:\/\2/' | sed -e 's/\//\\/g'
266     else
267       echo "$1" | sed -e "s?^$HOME?$DOSSYHOME?g" | sed -e 's/\\/\//g' | sed -e 's/\/cygdrive//' | sed -e 's/\/\([a-zA-Z]\)\/\(.*\)/\1:\/\2/'
268     fi
269   }
270   
271   # switches from an X:/ form to a /cygdrive/X/path form.  this is only useful
272   # for the cygwin environment currently.
273   function dos_to_unix_path() {
274     # we always remove dos slashes in favor of forward slashes.
275 #old:    echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\([a-zA-Z]\):\/\(.*\)/\/\1\/\2/'
276          echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\([a-zA-Z]\):\/\(.*\)/\/cygdrive\/\1\/\2/'
277   }
278
279   # returns a successful value (0) if this system is debian or ubuntu.
280   function debian_like() {
281     # decide if we think this is debian or ubuntu or a variant.
282     DEBIAN_LIKE=$(if [ ! -z "$(grep -i debian /etc/issue)" \
283         -o ! -z "$(grep -i ubuntu /etc/issue)" ]; then echo 1; else echo 0; fi)
284     if [ $DEBIAN_LIKE -eq 1 ]; then
285       # success; this is debianish.
286       return 0
287     else
288       # this seems like some other OS.
289       return 1
290     fi
291   }
292   
293   # su function: makes su perform a login.
294   # for some OSes, this transfers the X authority information to the new login.
295   function su() {
296     if debian_like; then
297       # debian currently requires the full version which imports X authority
298       # information for su.
299   
300       # get the x authority info for our current user.
301       source $FEISTY_MEOW_SCRIPTS/x_win/get_x_auth.sh
302   
303       if [ -z "$X_auth_info" ]; then
304         # if there's no authentication info to pass along, we just do a normal su.
305         /bin/su -l $*
306       else
307         # under X, we update the new login's authority info with the previous
308         # user's info.
309         (unset XAUTHORITY; /bin/su -l $* -c "$X_auth_info ; export DISPLAY=$DISPLAY ; bash")
310       fi
311     else
312       # non-debian supposedly doesn't need the extra overhead any more.
313       # or at least suse doesn't, which is the other one we've tested on.
314       /bin/su -l $*
315     fi
316   
317     # relabel the console after returning.
318     bash $FEISTY_MEOW_SCRIPTS/tty/label_terminal_with_infos.sh
319   }
320   
321   # sudo function wraps the normal sudo by ensuring we replace the terminal
322   # label if they're doing an su with the sudo.
323   function sudo() {
324     local first_command="$1"
325     /usr/bin/sudo "$@"
326     if [ "$first_command" == "su" ]; then
327       # yep, they were doing an su, but they're back now.
328       bash $FEISTY_MEOW_SCRIPTS/tty/label_terminal_with_infos.sh
329     fi
330   }
331   
332   # trashes the .#blah files that cvs and svn leave behind when finding conflicts.
333   # this kind of assumes you've already checked them for any salient facts.
334   function clean_cvs_junk() {
335     for i in $*; do
336       find $i -follow -type f -iname ".#*" -exec perl $FEISTY_MEOW_SCRIPTS/files/safedel.pl {} ";" 
337     done
338   }
339
340   # overlay for nechung binary so that we can complain less grossly about it when it's missing.
341   function nechung() {
342     local wheres_nechung=$(which nechung 2>/dev/null)
343     if [ -z "$wheres_nechung" ]; then
344       echo "The nechung oracle program cannot be found.  You may want to consider"
345       echo "rebuilding the feisty meow applications with this command:"
346       echo "bash $FEISTY_MEOW_SCRIPTS/generator/produce_feisty_meow.sh"
347     else
348       $wheres_nechung
349     fi
350   }
351   
352   # recreates all the generated files that the feisty meow scripts use.
353   function regenerate() {
354     # do the bootstrapping process again.
355     echo "regenerating feisty meow script environment."
356     bash $FEISTY_MEOW_SCRIPTS/core/reconfigure_feisty_meow.sh
357     echo
358     # force a full reload by turning off sentinel variable and alias.
359     # the nethack one is used by fred's customizations.
360     # interesting note perhaps: found that the NETHACKOPTIONS variable was
361     # not being unset correctly when preceded by an alias.  split them up
362     # like they are now due to that bug.
363     unset -v CORE_ALIASES_LOADED FEISTY_MEOW_LOADING_DOCK NECHUNG NETHACKOPTIONS 
364     unset -f function_sentinel 
365     # reload feisty meow environment in current shell.
366     source $FEISTY_MEOW_SCRIPTS/core/launch_feisty_meow.sh
367     # run nechung oracle to give user a new fortune.
368     nechung
369   }
370
371   # generates a random password where the first parameter is the number of characters
372   # in the password (default 20) and the second parameter specifies whether to use
373   # special characters (1) or not (0).
374   # found function at http://legroom.net/2010/05/06/bash-random-password-generator
375   function random_password()
376   {
377     [ "$2" == "0" ] && CHAR="[:alnum:]" || CHAR="[:graph:]"
378     cat /dev/urandom | tr -cd "$CHAR" | head -c ${1:-32}
379     echo
380   }
381
382   # a wrapper for the which command that finds items on the path.  some OSes
383   # do not provide which, so we want to not be spewing errors when that
384   # happens.
385   function whichable()
386   {
387     to_find="$1"; shift
388     which which &>/dev/null
389     if [ $? -ne 0 ]; then
390       # there is no which command here.  we produce nothing due to this.
391       echo
392     fi
393     echo $(which $to_find)
394   }
395
396   # copies a set of custom scripts into the proper location for feisty meow
397   # to merge their functions and aliases with the standard set.
398   function recustomize()
399   {
400     user="$1"; shift
401     if [ -z "$user" ]; then
402       # use our default example user if there was no name provided.
403       user=fred
404     fi
405     if [ ! -d "$FEISTY_MEOW_APEX/customizing/$user" ]; then
406       echo "The customization folder provided for $user should be:"
407       echo "  '$FEISTY_MEOW_APEX/customizing/$user'"
408       echo "but that folder does not exist.  Skipping customization."
409       return 1
410     fi
411     regenerate >/dev/null
412     pushd "$FEISTY_MEOW_LOADING_DOCK/custom" &>/dev/null
413     local incongruous_files="$(bash "$FEISTY_MEOW_SCRIPTS/files/list_non_dupes.sh" "$FEISTY_MEOW_APEX/customizing/$user" "$FEISTY_MEOW_LOADING_DOCK/custom")"
414
415 #echo "the incongruous files list is: $incongruous_files"
416     # disallow a single character result, since we get "*" as result when nothing exists yet.
417     if [ ${#incongruous_files} -ge 2 ]; then
418       echo "cleaning unknown older overrides..."
419       perl "$FEISTY_MEOW_SCRIPTS/files/safedel.pl" $incongruous_files
420       echo
421     fi
422     popd &>/dev/null
423     echo "copying custom overrides for $user"
424     mkdir -p "$FEISTY_MEOW_LOADING_DOCK/custom" 2>/dev/null
425     perl "$FEISTY_MEOW_SCRIPTS/text/cpdiff.pl" "$FEISTY_MEOW_APEX/customizing/$user" "$FEISTY_MEOW_LOADING_DOCK/custom"
426     if [ -d "$FEISTY_MEOW_APEX/customizing/$user/scripts" ]; then
427       echo "copying custom scripts for $user"
428       \cp -R "$FEISTY_MEOW_APEX/customizing/$user/scripts" "$FEISTY_MEOW_LOADING_DOCK/custom/"
429     fi
430     echo
431     regenerate
432   }
433
434 #uhhh, this does what now?
435   function add_cygwin_drive_mounts() {
436     for i in c d e f g h q z ; do
437       ln -s /cygdrive/$i $i
438     done
439   }
440
441   # takes a file to modify, and then it will replace any occurrences of the
442   # pattern provided as the second parameter with the text in the third
443   # parameter.
444   function replace_pattern_in_file()
445   {
446     local file="$1"; shift
447     local pattern="$1"; shift
448     local replacement="$1"; shift
449     if [ -z "$file" -o -z "$pattern" -o -z "$replacement" ]; then
450       echo "replace_pattern_in_file: needs a filename, a pattern to replace, and the"
451       echo "text to replace that pattern with."
452       return 1
453     fi
454     sed -i -e "s%$pattern%$replacement%g" "$file"
455   }
456
457   # goes to a particular directory passed as parameter 1, and then removes all
458   # the parameters after that from that directory.
459   function push_whack_pop()
460   {
461     local dir="$1"; shift
462     pushd "$dir" &>/dev/null
463     rm -rf $* &>/dev/null
464     popd &>/dev/null
465   }
466
467   function spacem()
468   {
469     while [ $# -gt 0 ]; do
470       arg="$1"; shift
471       if [ ! -f "$arg" -a ! -d "$arg" ]; then
472         echo "failure to find a file or directory named '$arg'."
473         continue
474       fi
475
476       # first we will capture the output of the character replacement operation for reporting.
477       # this is done first since some filenames can't be properly renamed in perl (e.g. if they
478       # have pipe characters apparently).
479       intermediate_name="$(bash "$FEISTY_MEOW_SCRIPTS/files/replace_spaces_with_underscores.sh" "$arg")"
480       local saw_intermediate_result=0
481       if [ -z "$intermediate_name" ]; then
482         # make sure we report something, if there are no further name changes.
483         intermediate_name="'$arg'"
484       else 
485         # now zap the first part of the name off (since original name isn't needed).
486         intermediate_name="$(echo $intermediate_name | sed -e 's/.*=> //')"
487         saw_intermediate_result=1
488       fi
489
490       # first we rename the file to be lower case.
491       actual_file="$(echo $intermediate_name | sed -e "s/'\([^']*\)'/\1/")"
492       final_name="$(perl $FEISTY_MEOW_SCRIPTS/files/renlower.pl "$actual_file")"
493       local saw_final_result=0
494       if [ -z "$final_name" ]; then
495         final_name="$intermediate_name"
496       else
497         final_name="$(echo $final_name | sed -e 's/.*=> //')"
498         saw_final_result=1
499       fi
500 #echo intermed=$saw_intermediate_result 
501 #echo final=$saw_final_result 
502
503       if [[ $saw_intermediate_result != 0 || $saw_final_result != 0 ]]; then
504         # printout the combined operation results.
505         echo "'$arg' => $final_name"
506       fi
507     done
508   }
509
510   ##############
511
512 # new breed of definer functions goes here.  still in progress.
513
514   # defines an alias and remembers that this is a new or modified definition.
515   # if the feisty meow codebase is unloaded, then so are all the aliases that
516   # were defined.
517   function define_yeti_alias()
518   {
519 # if alias exists already, save old value for restore,
520 # otherwise save null value for restore,
521 # have to handle unaliasing if there was no prior value of one
522 # we newly defined.
523 # add alias name to a list of feisty defined aliases.
524
525 #hmmm: first implem, just do the alias and get that working...
526 alias "${@}"
527
528
529 return 0
530   }
531
532   # defines a variable within the feisty meow environment and remembers that
533   # this is a new or modified definition.  if the feisty meow codebase is
534   # unloaded, then so are all the variables that were defined.
535   # this function always exports the variables it defines.
536 #  function define_yeti_variable()
537 #  {
538 ## if variable exists already, save old value for restore,
539 ## otherwise save null value for restore,
540 ## have to handle unsetting if there was no prior value of one
541 ## we newly defined.
542 ## add variable name to a list of feisty defined variables.
543 #
544 ##hmmm: first implem just sets it up and exports the variable.
545 ##  i.e., this method always exports.
546 #export "${@}" 
547 #
548 #
549 #return 0
550 #  }
551
552   ##############
553
554   # just shows a separator line for an 80 column console, or uses the first
555   # parameter as the number of columns to expect.
556   function separator()
557   {
558     count=$1; shift
559     if [ -z "$count" ]; then
560       count=79
561     fi
562     echo
563     for ((i=0; i < $count - 1; i++)); do
564       echo -n "="
565     done
566     echo
567     echo
568   }
569   # alias for separator.
570   function sep()
571   {
572     separator $*
573   }
574
575   ##############
576
577   function function_sentinel() { return 0; }
578   
579   if [ ! -z "$SHELL_DEBUG" ]; then echo "feisty meow function definitions done."; fi
580
581   ##############
582
583   # test code for set_var_if_undefined.
584   run_test=0
585   if [ $run_test != 0 ]; then
586     echo running tests on set_var_if_undefined.
587     flagrant=petunia
588     set_var_if_undefined flagrant forknordle
589     check_result "testing if defined variable would be whacked"
590     if [ $flagrant != petunia ]; then
591       echo set_var_if_undefined failed to leave the test variable alone
592       exit 1
593     fi
594     unset bobblehead_stomper
595     set_var_if_undefined bobblehead_stomper endurance
596     if [ $bobblehead_stomper != endurance ]; then
597       echo set_var_if_undefined failed to set a variable that was not defined yet
598       exit 1
599     fi
600   fi
601
602 fi
603