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