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