debugging term title again
[feisty_meow.git] / scripts / core / functions.sh
1 #!/bin/bash
2
3 # This defines some general, useful functions.
4
5 #hmmm: starting to get a bit beefy in here.  perhaps there is a good way to refactor the functions into more specific folders, if they aren't really totally general purpose?
6
7 ##############
8
9 # test whether we've been here before or not.
10 skip_all=
11 type function_sentinel &>/dev/null
12 if [ $? -eq 0 ]; then
13   # there was no error, so we can skip the inits.
14   if [ ! -z "$DEBUG_FEISTY_MEOW" ]; then
15     echo "skipping function definitions, because already defined."
16   fi
17   skip_all=yes
18 else
19   skip_all=
20 fi
21
22 if [ -z "$skip_all" ]; then
23
24   if [ ! -z "$DEBUG_FEISTY_MEOW" ]; then
25     echo "feisty meow function definitions beginning now..."
26   fi
27
28   # a handy little method that can be used for date strings.  it was getting
29   # really tiresome how many different ways the script did the date formatting.
30   function date_stringer() {
31     local sep="$1"; shift
32     if [ -z "$sep" ]; then sep='_'; fi
33     date +"%Y$sep%m$sep%d$sep%H%M$sep%S" | tr -d '/\n/'
34   }
35   
36   # makes a directory of the name specified and then tries to change the
37   # current directory to that directory.
38   function mcd() {
39     if [ ! -d "$1" ]; then mkdir -p "$1"; fi
40     cd "$1"
41   }
42
43   # returns true if the variable is an array.
44   function is_array() {
45     [[ "$(declare -p $1)" =~ "declare -a" ]]
46   }
47
48   # returns true if the name provided is a defined alias.
49   function is_alias() {
50     alias $1 &>/dev/null
51     return $?
52   }
53
54   # makes the status of pipe number N (passed as first parameter) into the
55   # main return value (i.e., the value for $?).  this is super handy to avoid
56   # repeating the awkward looking code below in multiple places.
57   function promote_pipe_return()
58   {
59     ( exit ${PIPESTATUS[$1]} )
60   }
61
62   ##############
63
64   # displays the value of a variable in bash friendly format.
65   function var() {
66     HOLDIFS="$IFS"
67     IFS=""
68     while true; do
69       local varname="$1"; shift
70       if [ -z "$varname" ]; then
71         break
72       fi
73
74       if is_alias "$varname"; then
75 #echo found $varname is alias
76         local tmpfile="$(mktemp $TMP/aliasout.XXXXXX)"
77         alias $varname | sed -e 's/.*=//' >$tmpfile
78         echo "alias $varname=$(cat $tmpfile)"
79         \rm $tmpfile
80       elif [ -z "${!varname}" ]; then
81         echo "$varname undefined"
82       else
83         if is_array "$varname"; then
84 #echo found $varname is array var 
85           local temparray
86           eval temparray="(\${$varname[@]})"
87           echo "$varname=(${temparray[@]})"
88 #hmmm: would be nice to print above with elements enclosed in quotes, so that we can properly
89 # see ones that have spaces in them.
90         else
91 #echo found $varname is simple
92           echo "$varname=${!varname}"
93         fi
94       fi
95     done | sort
96     IFS="$HOLDIFS"
97   }
98
99   ##############
100
101   # when passed a list of things, this will return the unique items from that list as an echo.
102   function uniquify()
103   {
104     # do the uniquification: split the space separated items into separate lines, then
105     # sort the list, then run the uniq tool on the list.  results will be packed back onto
106     # one line when invoked like: local fredlist="$(uniquify a b c e d a e f a e d b)"
107     echo $* | tr ' ' '\n' | sort | uniq
108   }
109
110   # sets the variable in parameter 1 to the value in parameter 2, but only if
111   # that variable was undefined.
112   function set_var_if_undefined()
113   {
114     local var_name="$1"; shift
115     local var_value="$1"; shift
116     if [ -z "${!var_name}" ]; then
117       eval export $var_name="$var_value"
118     fi
119   }
120
121   ##############
122
123   function success_sound()
124   {
125     if [ ! -z "$CLAM_FINISH_SOUND" ]; then
126       bash $FEISTY_MEOW_SCRIPTS/multimedia/sound_play.sh "$CLAM_FINISH_SOUND"
127     fi
128   }
129
130   function error_sound()
131   {
132     if [ ! -z "$CLAM_ERROR_SOUND" ]; then
133       bash $FEISTY_MEOW_SCRIPTS/multimedia/sound_play.sh "$CLAM_ERROR_SOUND"
134     fi
135   }
136
137   ##############
138
139   # echoes the maximum number of columns that the terminal supports.  usually
140   # anything you print to the terminal with length less than (but not equal to)
141   # maxcols will never wrap.
142   function get_maxcols()
143   {
144     # calculate the number of columsn in the terminal.
145     local cols=$(stty size | awk '{print $2}')
146     echo $cols
147   }
148
149   ##############
150
151   # checks the result of the last command that was run, and if that failed,
152   # then this complains and exits from bash.  the function parameters are
153   # used as the message to print as a complaint.
154   function exit_on_error()
155   {
156     if [ $? -ne 0 ]; then
157       echo -e "\n\nan important action failed and this script will stop:\n\n$*\n\n*** Exiting script..."
158       error_sound
159       exit 1
160     fi
161   }
162
163   # like exit_on_error, but will keep going after complaining.
164   function continue_on_error()
165   {
166     if [ $? -ne 0 ]; then
167       echo -e "\n\na problem occurred, but we can continue:\n\n$*\n\n=> Continuing script..."
168       error_sound
169     fi
170   }
171
172   ##############
173
174   # accepts any number of arguments and outputs them to the feisty meow event log.
175   function log_feisty_meow_event()
176   {
177     echo -e "$(date_stringer) -- ${USER}@$(hostname): $*" >> "$FEISTY_MEOW_EVENT_LOG"
178   }
179
180   ##############
181
182   # wraps secure shell with some parameters we like, most importantly to enable X forwarding.
183   function ssh()
184   {
185     local args=($*)
186     # we remember the old terminal title, then force the TERM variable to a more generic
187     # version for the other side (just 'linux'); we don't want the remote side still
188     # thinking it's running xterm.
189     save_terminal_title
190 echo TERM saved is $PRIOR_TERMINAL_TITLE
191 #hmmm: why were we doing this?  it scorches the user's logged in session, leaving it without proper terminal handling.
192 #    # we save the value of TERM; we don't want to leave the user's terminal
193 #    # brain dead once we come back from this function.
194 #    local oldterm="$TERM"
195 #    export TERM=linux
196     /usr/bin/ssh -X -C "${args[@]}"
197 #    # restore the terminal variable also.
198 #    TERM="$oldterm"
199 echo TERM prior to restore is $PRIOR_TERMINAL_TITLE
200     restore_terminal_title
201 echo TERM title restored
202   }
203
204   ##############
205
206   # locates a process given a search pattern to match in the process list.
207   # supports a single command line flag style parameter of "-u USERNAME";
208   # if the -u flag is found, a username is expected afterwards, and only the
209   # processes of that user are considered.
210   function psfind() {
211     local -a patterns=("${@}")
212 #echo ====
213 #echo patterns list is: "${patterns[@]}"
214 #echo ====
215
216     local user_flag
217     if [ "${patterns[0]}" == "-u" ]; then
218       user_flag="-u ${patterns[1]}" 
219 #echo "found a -u parm and user=${patterns[1]}" 
220       # void the two elements with that user flag so we don't use them as patterns.
221       unset patterns[0] patterns[1]=
222     else
223       # select all users.
224       user_flag="-e"
225     fi
226
227     local PID_DUMP="$(mktemp "$TMP/zz_pidlist.XXXXXX")"
228     local -a PIDS_SOUGHT
229
230     if [ "$OS" == "Windows_NT" ]; then
231       # gets cygwin's (god awful) ps to show windoze processes also.
232       local EXTRA_DOZER_FLAGS="-W"
233       # pattern to use for peeling off the process numbers.
234       local pid_finder_pattern='s/ *\([0-9][0-9]*\) *.*$/\1/p'
235
236     else
237       # flags which clean up the process listing output on unixes.
238       # apparently cygwin doesn't count as a type of unix, because their
239       # crummy specialized ps command doesn't support normal ps flags.
240       local EXTRA_UNIX_FLAGS="-o pid,args"
241       # pattern to use for peeling off the process numbers.
242       local pid_finder_pattern='s/^[[:space:]]*\([0-9][0-9]*\).*$/\1/p'
243     fi
244
245     /bin/ps $EXTRA_DOZER_FLAGS $EXTRA_UNIX_FLAGS $user_flag | tail -n +2 >$PID_DUMP
246 #echo ====
247 #echo got all this stuff in the pid dump file:
248 #cat $PID_DUMP
249 #echo ====
250
251     # search for the pattern the user wants to find, and just pluck the process
252     # ids out of the results.
253     local i
254     for i in "${patterns[@]}"; do
255       PIDS_SOUGHT+=($(cat $PID_DUMP \
256         | grep -i "$i" \
257         | sed -n -e "$pid_finder_pattern"))
258     done
259 #echo ====
260 #echo pids sought list became:
261 #echo "${PIDS_SOUGHT[@]}"
262 #echo ====
263
264     if [ ${#PIDS_SOUGHT[*]} -ne 0 ]; then
265       local PIDS_SOUGHT2=$(printf -- '%s\n' ${PIDS_SOUGHT[@]} | sort | uniq)
266       PIDS_SOUGHT=()
267       PIDS_SOUGHT=${PIDS_SOUGHT2[*]}
268       echo ${PIDS_SOUGHT[*]}
269     fi
270     /bin/rm $PID_DUMP
271   }
272   
273   # finds all processes matching the pattern specified and shows their full
274   # process listing (whereas psfind just lists process ids).
275   function psa() {
276     if [ -z "$1" ]; then
277       echo "psa finds processes by pattern, but there was no pattern on the command line."
278       return 1
279     fi
280     local -a patterns=("${@}")
281     p=$(psfind "${patterns[@]}")
282     if [ -z "$p" ]; then
283       # no matches.
284       return 0
285     fi
286
287     if [ "${patterns[0]}" == "-u" ]; then
288       # void the two elements with that user flag so we don't use them as patterns.
289       unset patterns[0] patterns[1]=
290     fi
291
292     echo ""
293     echo "Processes matching ${patterns[@]}..."
294     echo ""
295     if [ -n "$IS_DARWIN" ]; then
296       unset fuzil_sentinel
297       for i in $p; do
298         # only print the header the first time.
299         if [ -z "$fuzil_sentinel" ]; then
300           ps $i -w -u
301         else
302           ps $i -w -u | sed -e '1d'
303         fi
304         fuzil_sentinel=true
305       done
306     else 
307       # cases besides mac os x's darwin.
308       if [ "$OS" == "Windows_NT" ]; then
309         # special case for windows.
310         ps | head -1
311         for curr in $p; do
312           ps -W -p $curr | tail -n +2
313         done
314       else
315         # normal OSes can handle a nice simple query.
316         ps wu $p
317       fi
318     fi
319   }
320   
321   ##############
322
323 #hmmm: holy crowbars, this is an old one.  do we ever still have any need of it?
324   # an unfortunately similarly named function to the above 'ps' as in process
325   # methods, but this 'ps' stands for postscript.  this takes a postscript file
326   # and converts it into pcl3 printer language and then ships it to the printer.
327   # this mostly makes sense for an environment where one's default printer is
328   # pcl.  if the input postscript causes ghostscript to bomb out, there has been
329   # some good success running ps2ps on the input file and using the cleaned
330   # postscript file for printing.
331   function ps2pcl2lpr() {
332     for $i in $*; do
333       gs -sDEVICE=pcl3 -sOutputFile=- -sPAPERSIZE=letter "$i" | lpr -l 
334     done
335   }
336   
337 #hmmm: not really doing anything yet; ubuntu seems to have changed from pulseaudio in 17.04?
338   # restarts the sound driver.
339   function fix_sound_driver() {
340     # stop bash complaining about blank function body.
341     local nothing=
342 #if alsa something
343 #    sudo service alsasound restart
344 #elif pulse something
345 #    sudo pulseaudio -k
346 #    sudo pulseaudio -D
347 #else
348 #    something else...?
349 #fi
350
351   }
352
353   function screen() {
354     save_terminal_title
355 #hmmm: ugly absolute path here.
356     /usr/bin/screen $*
357     restore_terminal_title
358   }
359   
360   # switches from a /X/path form to an X:/ form.  this also processes cygwin paths.
361   function unix_to_dos_path() {
362     # we usually remove dos slashes in favor of forward slashes.
363     local DOSSYHOME
364     if [[ ! "$OS" =~ ^[Ww][iI][nN] ]]; then
365       # fake this value for non-windows (non-cygwin) platforms.
366       DOSSYHOME="$HOME"
367     else
368       # for cygwin, we must replace the /home/X path with an absolute one, since cygwin
369       # insists on the /home form instead of /c/cygwin/home being possible.  this is
370       # super frustrating and nightmarish.
371       DOSSYHOME="$(cygpath -am "$HOME")"
372     fi
373
374     if [ ! -z "$SERIOUS_SLASH_TREATMENT" ]; then
375       # unless this flag is set, in which case we force dos slashes.
376       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'
377     else
378       echo "$1" | sed -e "s?^$HOME?$DOSSYHOME?g" | sed -e 's/\\/\//g' | sed -e 's/\/cygdrive//' | sed -e 's/\/\([a-zA-Z]\)\/\(.*\)/\1:\/\2/'
379     fi
380   }
381   
382   # switches from an X:/ form to a /cygdrive/X/path form.  this is only useful
383   # for the cygwin environment currently.
384   function dos_to_unix_path() {
385     # we always remove dos slashes in favor of forward slashes.
386 #old:    echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\([a-zA-Z]\):\/\(.*\)/\/\1\/\2/'
387          echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\([a-zA-Z]\):\/\(.*\)/\/cygdrive\/\1\/\2/'
388   }
389
390   # returns a successful value (0) if this system is debian or ubuntu.
391   function debian_like() {
392     # decide if we think this is debian or ubuntu or a variant.
393     DEBIAN_LIKE=$(if [ ! -z "$(grep -i debian /etc/issue)" \
394         -o ! -z "$(grep -i ubuntu /etc/issue)" ]; then echo 1; else echo 0; fi)
395     if [ $DEBIAN_LIKE -eq 1 ]; then
396       # success; this is debianish.
397       return 0
398     else
399       # this seems like some other OS.
400       return 1
401     fi
402   }
403   
404   # su function: makes su perform a login.
405   # for some OSes, this transfers the X authority information to the new login.
406   function su() {
407     if debian_like; then
408       # debian currently requires the full version which imports X authority
409       # information for su.
410   
411       # get the x authority info for our current user.
412       source "$FEISTY_MEOW_SCRIPTS/security/get_x_auth.sh"
413   
414       if [ -z "$X_auth_info" ]; then
415         # if there's no authentication info to pass along, we just do a normal su.
416         /bin/su -l $*
417       else
418         # under X, we update the new login's authority info with the previous
419         # user's info.
420         (unset XAUTHORITY; /bin/su -l $* -c "$X_auth_info ; export DISPLAY=$DISPLAY ; bash")
421       fi
422     else
423       # non-debian supposedly doesn't need the extra overhead any more.
424       # or at least suse doesn't, which is the other one we've tested on.
425       /bin/su -l $*
426     fi
427   }
428   
429   # sudo function wraps the normal sudo by ensuring we replace the terminal
430   # label if they're doing an su with the sudo.
431   function sudo() {
432     save_terminal_title
433     /usr/bin/sudo "$@"
434     retval=$?
435     restore_terminal_title
436 #    if [ "$first_command" == "su" ]; then
437 #      # yep, they were doing an su, but they're back now.
438 #      label_terminal_with_info
439 #    fi
440     return $retval
441   }
442   
443   # trashes the .#blah files that cvs and subversion leave behind when finding conflicts.
444   # this kind of assumes you've already checked them for any salient facts.
445   function clean_cvs_junk() {
446     for i in $*; do
447       find $i -follow -type f -iname ".#*" -exec perl $FEISTY_MEOW_SCRIPTS/files/safedel.pl {} ";" 
448     done
449   }
450
451   # overlay for nechung binary so that we can complain less grossly about it when it's missing.
452   function nechung() {
453     local wheres_nechung=$(which nechung 2>/dev/null)
454     if [ -z "$wheres_nechung" ]; then
455       echo "The nechung oracle program cannot be found.  You may want to consider"
456       echo "rebuilding the feisty meow applications with this command:"
457       echo "bash $FEISTY_MEOW_SCRIPTS/generator/produce_feisty_meow.sh"
458       echo
459     else
460       $wheres_nechung
461     fi
462   }
463   
464   # recreates all the generated files that the feisty meow scripts use.
465   function regenerate() {
466     # do the bootstrapping process again.
467     save_terminal_title
468     echo "regenerating feisty meow script environment."
469     bash $FEISTY_MEOW_SCRIPTS/core/reconfigure_feisty_meow.sh
470     echo
471     # force a full reload by turning off sentinel variables and methods.
472     unset -v CORE_VARIABLES_LOADED FEISTY_MEOW_LOADING_DOCK USER_CUSTOMIZATIONS_LOADED
473     unalias CORE_ALIASES_LOADED &>/dev/null
474     unset -f function_sentinel 
475     # reload feisty meow environment in current shell.
476     log_feisty_meow_event "reloading the feisty meow scripts for $USER in current shell."
477     source "$FEISTY_MEOW_SCRIPTS/core/launch_feisty_meow.sh"
478     # run nechung oracle to give user a new fortune.
479     nechung
480     restore_terminal_title
481   }
482
483   # copies a set of custom scripts into the proper location for feisty meow
484   # to merge their functions and aliases with the standard set.
485   function recustomize()
486   {
487     local custom_user="$1"; shift
488     if [ -z "$custom_user" ]; then
489       # default to login name if there was no name provided.
490       custom_user="$(logname)"
491         # we do intend to use logname here to get the login name and to ignore
492         # if the user has sudo root access; we don't want to provide a custom
493         # profile for root.
494     fi
495
496     save_terminal_title
497
498     if [ ! -d "$FEISTY_MEOW_SCRIPTS/customize/$custom_user" ]; then
499       echo -e "the customization folder for '$custom_user' is missing:
500
501     $FEISTY_MEOW_SCRIPTS/customize/$custom_user
502
503 we will skip recustomization, but these other customizations are available:
504 "
505       # a little tr and sed magic to fix the carriage returns into commas.
506       local line="$(find $FEISTY_MEOW_SCRIPTS/customize -mindepth 1 -maxdepth 1 -type d -exec basename {} ';' | tr '\n' '&' | sed 's/&/, /g' | sed -e 's/, $//')"
507         # make the line feeds and carriage returns manageable with tr.
508         # convert the ampersand, our weird replacement for EOL, with a comma + space in sed.
509         # last touch with sed removes the last comma.
510       echo "    $line"
511       return 1
512     fi
513
514     # prevent permission foul-ups.
515     my_user="$USER"
516       # here we definitely want the effective user name (in USER), since
517       # we don't want, say, fred (as logname) to own all of root's loading
518       # dock stuff.
519     chown -R "$my_user:$my_user" \
520         "$FEISTY_MEOW_LOADING_DOCK"/* "$FEISTY_MEOW_GENERATED_STORE"/* 2>/dev/null
521     continue_on_error "chowning feisty meow generated directories to $my_user"
522
523     regenerate >/dev/null
524     pushd "$FEISTY_MEOW_LOADING_DOCK/custom" &>/dev/null
525     incongruous_files="$(bash "$FEISTY_MEOW_SCRIPTS/files/list_non_dupes.sh" "$FEISTY_MEOW_SCRIPTS/customize/$custom_user" "$FEISTY_MEOW_LOADING_DOCK/custom")"
526
527     local fail_message="\n
528 are the perl dependencies installed?  if you're on ubuntu or debian, try this:\n
529     $(grep "apt-get.*perl" $FEISTY_MEOW_APEX/readme.txt)\n
530 or if you're on cygwin, then try this (if apt-cyg is available):\n
531     $(grep "apt-cyg.*perl" $FEISTY_MEOW_APEX/readme.txt)\n";
532
533     #echo "the incongruous files list is: $incongruous_files"
534     # disallow a single character result, since we get "*" as result when nothing exists yet.
535     if [ ${#incongruous_files} -ge 2 ]; then
536       log_feisty_meow_event "cleaning unknown older overrides..."
537       perl "$FEISTY_MEOW_SCRIPTS/files/safedel.pl" $incongruous_files
538       continue_on_error "running safedel.  $fail_message" 
539     fi
540     popd &>/dev/null
541     log_feisty_meow_event "copying custom overrides for $custom_user"
542     mkdir -p "$FEISTY_MEOW_LOADING_DOCK/custom" 2>/dev/null
543     perl "$FEISTY_MEOW_SCRIPTS/text/cpdiff.pl" "$FEISTY_MEOW_SCRIPTS/customize/$custom_user" "$FEISTY_MEOW_LOADING_DOCK/custom"
544     continue_on_error "running cpdiff.  $fail_message"
545
546     if [ -d "$FEISTY_MEOW_SCRIPTS/customize/$custom_user/scripts" ]; then
547       log_feisty_meow_event "copying custom scripts for $custom_user"
548 #hmmm: could save output to show if an error occurs.
549       rsync -avz "$FEISTY_MEOW_SCRIPTS/customize/$custom_user/scripts" "$FEISTY_MEOW_LOADING_DOCK/custom/" &>/dev/null
550       continue_on_error "copying customization scripts"
551     fi
552     regenerate
553
554     # prevent permission foul-ups, again.
555     chown -R "$my_user:$my_user" \
556         "$FEISTY_MEOW_LOADING_DOCK" "$FEISTY_MEOW_GENERATED_STORE" 2>/dev/null
557     continue_on_error "once more chowning feisty meow generated directories to $my_user"
558
559     restore_terminal_title
560   }
561
562   # generates a random password where the first parameter is the number of characters
563   # in the password (default 20) and the second parameter specifies whether to use
564   # special characters (1) or not (0).
565   # found function at http://legroom.net/2010/05/06/bash-random-password-generator
566   function random_password()
567   {
568     [ "$2" == "0" ] && CHAR="[:alnum:]" || CHAR="[:graph:]"
569     cat /dev/urandom | tr -cd "$CHAR" | head -c ${1:-32}
570     echo
571   }
572
573   # a wrapper for the which command that finds items on the path.  some OSes
574   # do not provide which, so we want to not be spewing errors when that
575   # happens.
576   function whichable()
577   {
578     to_find="$1"; shift
579     which which &>/dev/null
580     if [ $? -ne 0 ]; then
581       # there is no which command here.  we produce nothing due to this.
582       echo
583     fi
584     echo $(which $to_find)
585   }
586
587   function add_cygwin_drive_mounts() {
588     for i in c d e f g h q z ; do
589 #hmmm: improve this by not adding the link if already there, or if the drive is not valid.
590       ln -s /cygdrive/$i $i
591     done
592   }
593
594   ############################
595
596   # takes a file to modify, and then it will replace any occurrences of the
597   # pattern provided as the second parameter with the text in the third
598   # parameter.
599   function replace_pattern_in_file()
600   {
601     local file="$1"; shift
602     local pattern="$1"; shift
603     local replacement="$1"; shift
604     if [ -z "$file" -o -z "$pattern" -o -z "$replacement" ]; then
605       echo "replace_pattern_in_file: needs a filename, a pattern to replace, and the"
606       echo "text to replace that pattern with."
607       return 1
608     fi
609     sed -i -e "s%$pattern%$replacement%g" "$file"
610   }
611
612   # similar to replace_pattern_in_file, but also will add the new value
613   # when the old one did not already exist in the file.
614   function replace_if_exists_or_add()
615   {
616     local file="$1"; shift
617     local phrase="$1"; shift
618     local replacement="$1"; shift
619     if [ -z "$file" -o ! -f "$file" -o -z "$phrase" -o -z "$replacement" ]; then
620       echo "replace_if_exists_or_add: needs a filename, a phrase to replace, and the"
621       echo "text to replace that phrase with."
622       return 1
623     fi
624     grep "$phrase" "$file" >/dev/null
625     # replace if the phrase is there, otherwise add it.
626     if [ $? -eq 0 ]; then
627       replace_pattern_in_file "$file" "$phrase" "$replacement"
628     else
629       # this had better be the complete line.
630       echo "$replacement" >>"$file"
631     fi
632   }
633
634   ############################
635
636   # finds a variable (first parameter) in a particular property file
637   # (second parameter).  the expected format for the file is:
638   # varX=valueX
639   function seek_variable()
640   {
641     local find_var="$1"; shift
642     local file="$1"; shift
643     if [ -z "$find_var" -o -z "$file" -o ! -f "$file" ]; then
644       echo -e "seek_variable: needs two parameters, firstly a variable name, and\nsecondly a file where the variable's value will be sought." 1>&2
645       return 1
646     fi
647   
648     while read line; do
649       if [ ${#line} -eq 0 ]; then continue; fi
650       # split the line into the variable name and value.
651       IFS='=' read -a assignment <<< "$line"
652       local var="${assignment[0]}"
653       local value="${assignment[1]}"
654       if [ "${value:0:1}" == '"' ]; then
655         # assume the entry was in quotes and remove them.
656         value="${value:1:$((${#value} - 2))}"
657       fi
658       if [ "$find_var" == "$var" ]; then
659         echo "$value"
660       fi
661     done < "$file"
662   }
663   
664   # finds a variable (first parameter) in a particular XML format file
665   # (second parameter).  the expected format for the file is:
666   # ... name="varX" value="valueX" ...
667   function seek_variable_in_xml()
668   {
669     local find_var="$1"; shift
670     local file="$1"; shift
671     if [ -z "$find_var" -o -z "$file" -o ! -f "$file" ]; then
672       echo "seek_variable_in_xml: needs two parameters, firstly a variable name, and"
673       echo "secondly an XML file where the variable's value will be sought."
674       return 1
675     fi
676   
677     while read line; do
678       if [ ${#line} -eq 0 ]; then continue; fi
679       # process the line to make it more conventional looking.
680       line="$(echo "$line" | sed -e 's/.*name="\([^"]*\)" value="\([^"]*\)"/\1=\2/')"
681       # split the line into the variable name and value.
682       IFS='=' read -a assignment <<< "$line"
683       local var="${assignment[0]}"
684       local value="${assignment[1]}"
685       if [ "${value:0:1}" == '"' ]; then
686         # assume the entry was in quotes and remove them.
687         value="${value:1:$((${#value} - 2))}"
688       fi
689       if [ "$find_var" == "$var" ]; then
690         echo "$value"
691       fi
692     done < "$file"
693   }
694   
695   ############################
696
697   # goes to a particular directory passed as parameter 1, and then removes all
698   # the parameters after that from that directory.
699   function push_whack_pop()
700   {
701     local dir="$1"; shift
702     pushd "$dir" &>/dev/null
703     if [ $? -ne 0 ]; then echo failed to enter dir--quitting.; fi
704     rm -rf $* &>/dev/null
705     if [ $? -ne 0 ]; then echo received a failure code when removing.; fi
706     popd &>/dev/null
707   }
708
709   function spacem()
710   {
711     while [ $# -gt 0 ]; do
712       arg="$1"; shift
713       if [ ! -f "$arg" -a ! -d "$arg" ]; then
714         echo "failure to find a file or directory named '$arg'."
715         continue
716       fi
717
718       # first we will capture the output of the character replacement operation for reporting.
719       # this is done first since some filenames can't be properly renamed in perl (e.g. if they
720       # have pipe characters apparently).
721       intermediate_name="$(bash "$FEISTY_MEOW_SCRIPTS/files/replace_spaces_with_underscores.sh" "$arg")"
722       local saw_intermediate_result=0
723       if [ -z "$intermediate_name" ]; then
724         # make sure we report something, if there are no further name changes.
725         intermediate_name="'$arg'"
726       else 
727         # now zap the first part of the name off (since original name isn't needed).
728         intermediate_name="$(echo $intermediate_name | sed -e 's/.*=> //')"
729         saw_intermediate_result=1
730       fi
731
732       # first we rename the file to be lower case.
733       actual_file="$(echo $intermediate_name | sed -e "s/'\([^']*\)'/\1/")"
734       final_name="$(perl $FEISTY_MEOW_SCRIPTS/files/renlower.pl "$actual_file")"
735       local saw_final_result=0
736       if [ -z "$final_name" ]; then
737         final_name="$intermediate_name"
738       else
739         final_name="$(echo $final_name | sed -e 's/.*=> //')"
740         saw_final_result=1
741       fi
742 #echo intermed=$saw_intermediate_result 
743 #echo final=$saw_final_result 
744
745       if [[ $saw_intermediate_result != 0 || $saw_final_result != 0 ]]; then
746         # printout the combined operation results.
747         echo "'$arg' => $final_name"
748       fi
749     done
750   }
751
752   ##############
753
754 # new breed of definer functions goes here.  still in progress.
755
756   # defines an alias and remembers that this is a new or modified definition.
757   # if the feisty meow codebase is unloaded, then so are all the aliases that
758   # were defined.
759   function define_yeti_alias()
760   {
761 # if alias exists already, save old value for restore,
762 # otherwise save null value for restore,
763 # have to handle unaliasing if there was no prior value of one
764 # we newly defined.
765 # add alias name to a list of feisty defined aliases.
766
767 #hmmm: first implem, just do the alias and get that working...
768 alias "${@}"
769
770
771 return 0
772   }
773
774   ##############
775
776 #hmmm: this points to an extended functions file being needed; not all of these are core.
777
778   # displays documentation in "md" formatted files.
779   function show_md()
780   {
781     local file="$1"; shift
782     pandoc "$file" | lynx -stdin
783   }
784
785   ##############
786
787   # just shows a separator line for an 80 column console, or uses the first
788   # parameter as the number of columns to expect.
789   function separator()
790   {
791     count=$1; shift
792     if [ -z "$count" ]; then
793       count=79
794     fi
795     echo
796     local i
797     for ((i=0; i < $count - 1; i++)); do
798       echo -n "="
799     done
800     echo
801     echo
802   }
803   # alias for separator.
804   function sep()
805   {
806     separator $*
807   }
808
809   ##############
810
811   # count the number of sub-directories in a directory and echo the result.
812   function count_directories()
813   {
814     local subbydir="$1"; shift
815     numdirs="$(find "$subbydir" -mindepth 1 -maxdepth 1 -type d | wc -l)"
816     echo $numdirs
817   }
818
819   # takes a string and capitalizes just the first character.  any capital letters in the remainder of
820   # the string are made lower case.  the processed string is returned by an echo.
821   function capitalize_first_char()
822   {
823     local to_dromedary="$1"; shift
824     to_dromedary="$(tr '[:lower:]' '[:upper:]' <<< ${to_dromedary:0:1})$(tr '[:upper:]' '[:lower:]' <<< ${to_dromedary:1})"
825     echo "$to_dromedary"
826   }
827
828   # given a source path and a target path, this will make a symbolic link from
829   # the source to the destination, but only if the source actually exists.
830   function make_safe_link()
831   {
832     local src="$1"; shift
833     local target="$1"; shift
834   
835     if [ -d "$src" ]; then
836       ln -s "$src" "$target"
837       exit_on_error "Creating symlink from '$src' to '$target'"
838     fi
839     echo "Created symlink from '$src' to '$target'."
840   }
841
842   # pretty prints the json files provided as parameters.
843   function clean_json()
844   {
845     if [ -z "$*" ]; then return; fi
846     local show_list=()
847     while true; do
848       local file="$1"; shift
849       if [ -z "$file" ]; then break; fi
850       if [ ! -f "$file" ]; then "echo File '$file' does not exist."; continue; fi
851       temp_out="$TMP/$file.view"
852       cat "$file" | python -m json.tool > "$temp_out"
853       show_list+=($temp_out)
854       continue_on_error "pretty printing '$file'"
855     done
856     filedump "${show_list[@]}"
857     rm "${show_list[@]}"
858   }
859
860   function json_text()
861   {
862     # only print our special headers or text fields.
863     local CR=$'\r'
864     local LF=$'\n'
865     clean_json $* |
866         grep -i "\"text\":\|^=.*" | 
867         sed -e "s/\\\\r/$CR/g" -e "s/\\\\n/\\$LF/g"
868   }
869
870   ##############
871
872   # echoes the machine's hostname.  can be used like so:
873   #   local my_host=$(get_hostname)
874   function get_hostname()
875   {
876     # there used to be more variation in how to do this, but adopting mingw
877     # and cygwin tools really helped out.
878     local this_host=unknown
879     if [ "$OS" == "Windows_NT" ]; then
880       this_host=$(hostname)
881     elif [ ! -z "$(echo $MACHTYPE | grep apple)" ]; then
882       this_host=$(hostname)
883     elif [ ! -z "$(echo $MACHTYPE | grep suse)" ]; then
884       this_host=$(hostname --long)
885     elif [ -x "$(which hostname 2>/dev/null)" ]; then
886       this_host=$(hostname)
887     fi
888     echo "$this_host"
889   }
890
891   # makes sure that the provided "folder" is a directory and is writable.
892   function test_writeable()
893   {
894     local folder="$1"; shift
895     if [ ! -d "$folder" -o ! -w "$folder" ]; then return 1; fi
896     return 0
897   }
898
899   ##############
900
901   # given a filename and a string to seek and a number of lines, then this
902   # function will remove the first occurrence of a line in the file that
903   # matches the string, and it will also axe the next N lines as specified.
904   function create_chomped_copy_of_file()
905   {
906     local filename="$1"; shift
907     local seeker="$1"; shift
908     local numlines=$1; shift
909
910 #echo into create_chomped_copy...
911 #var filename seeker numlines 
912
913     # make a backup first, oy.
914     \cp -f "$filename" "/tmp/$(basename ${filename}).bkup-${RANDOM}" 
915     exit_on_error "backing up file: $filename"
916
917     # make a temp file to write to before we move file into place in bind.
918     local new_version="/tmp/$(basename ${filename}).bkup-${RANDOM}" 
919     \rm -f "$new_version"
920     exit_on_error "cleaning out new version of file from: $new_version"
921
922     local line
923     local skip_count=0
924     local found_any=
925     while read line; do
926       # don't bother looking at the lines if we're already in skip mode.
927       if [[ $skip_count == 0 ]]; then
928         # find the string they're seeking.
929         if [[ ! "$line" =~ .*${seeker}.* ]]; then
930           # no match.
931           echo "$line" >> "$new_version"
932         else
933           # a match!  start skipping.  we will delete this line and the next N lines.
934           ((skip_count++))
935 #echo first skip count is now $skip_count
936           found_any=yes
937         fi
938       else
939         # we're already skipping.  let's keep going until we hit the limit.
940         ((skip_count++))
941 #echo ongoing skip count is now $skip_count
942         if (( $skip_count > $numlines )); then
943           echo "Done skipping, and back to writing output file."
944           skip_count=0
945         fi
946       fi
947     done < "$filename"
948
949 #echo file we created looks like this:
950 #cat "$new_version"
951
952     if [ ! -z "$found_any" ]; then
953       # put the file back into place under the original name.
954       \mv "$new_version" "$filename"
955       exit_on_error "moving the new version into place in: $filename"
956     else
957       # cannot always be considered an error, but we can at least gripe.
958       echo "Did not find any matches for seeker '$seeker' in file: $filename"
959     fi
960   }
961
962   ##############
963
964   # site avenger aliases
965   function switchto()
966   {
967     THISDIR="$FEISTY_MEOW_SCRIPTS/site_avenger"
968     source "$FEISTY_MEOW_SCRIPTS/site_avenger/shared_site_mgr.sh"
969     switch_to "$1"
970   }
971
972   ##############
973
974   # NOTE: no more function definitions are allowed after this point.
975
976   function function_sentinel()
977   {
978     return 0; 
979   }
980   
981   if [ ! -z "$DEBUG_FEISTY_MEOW" ]; then echo "feisty meow function definitions done."; fi
982
983   ##############
984
985   # test code for set_var_if_undefined.
986   run_test=0
987   if [ $run_test != 0 ]; then
988     echo running tests on set_var_if_undefined.
989     flagrant=petunia
990     set_var_if_undefined flagrant forknordle
991     exit_on_error "testing if defined variable would be whacked"
992     if [ $flagrant != petunia ]; then
993       echo set_var_if_undefined failed to leave the test variable alone
994       exit 1
995     fi
996     unset bobblehead_stomper
997     set_var_if_undefined bobblehead_stomper endurance
998     if [ $bobblehead_stomper != endurance ]; then
999       echo set_var_if_undefined failed to set a variable that was not defined yet
1000       exit 1
1001     fi
1002   fi
1003
1004 fi
1005