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