improved reload, where incorrect usage of alias on a function was just always reloadi...
[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 functions.sh 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 function definitions begin...
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   # displays the value of a variable in bash friendly format.
38   function var() {
39     while true; do
40       local varname="$1"; shift
41       if [ -z "$varname" ]; then
42         break
43       fi
44       if [ -z "${!varname}" ]; then
45         echo "$varname undefined"
46       else
47         echo "$varname=${!varname}"
48       fi
49     done
50   }
51
52   function success_sound()
53   {
54     if [ ! -z "$CLAM_FINISH_SOUND" ]; then
55       bash $FEISTY_MEOW_SCRIPTS/multimedia/sound_play.sh "$CLAM_FINISH_SOUND"
56     fi
57   }
58
59   function error_sound()
60   {
61     if [ ! -z "$CLAM_ERROR_SOUND" ]; then
62       bash $FEISTY_MEOW_SCRIPTS/multimedia/sound_play.sh "$CLAM_ERROR_SOUND"
63     fi
64   }
65
66   # checks the result of the last command that was run, and if that failed,
67   # then this complains and exits from bash.  the function parameters are
68   # used as the message to print as a complaint.
69   function check_result()
70   {
71     if [ $? -ne 0 ]; then
72       echo -e "failed on: $*"
73       error_sound
74       exit 1
75     fi
76   }
77
78   # locates a process given a search pattern to match in the process list.
79   function psfind() {
80     local -a patterns=("${@}")
81     local PID_DUMP="$(mktemp "$TMP/zz_pidlist.XXXXXX")"
82     local -a PIDS_SOUGHT
83     if [ "$OS" == "Windows_NT" ]; then
84       # needs to be a windows format filename for 'type' to work.
85       if [ ! -d c:/tmp ]; then
86         mkdir c:/tmp
87       fi
88       # windows7 magical mystery tour lets us create a file c:\\tmp_pids.txt, but then it's not
89       # really there in the root of drive c: when we look for it later.  hoping to fix that
90       # problem by using a subdir, which also might be magical thinking from windows perspective.
91       tmppid=c:\\tmp\\pids.txt
92       # we have abandoned all hope of relying on ps on windows.  instead we use wmic to get full
93       # command lines for processes.
94       wmic /locale:ms_409 PROCESS get processid,commandline </dev/null >"$tmppid"
95       local flag='/c'
96       if [ ! -z "$(uname -a | grep "^MING" )" ]; then
97         flag='//c'
98       fi
99       # we 'type' the file to get rid of the unicode result from wmic.
100       cmd $flag type "$tmppid" >$PID_DUMP
101       \rm "$tmppid"
102       local appropriate_pattern="s/^.*  *\([0-9][0-9]*\) *\$/\1/p"
103       for i in "${patterns[@]}"; do
104         PIDS_SOUGHT+=($(cat $PID_DUMP \
105           | grep -i "$i" \
106           | sed -n -e "$appropriate_pattern"))
107       done
108     else
109       /bin/ps $extra_flags wuax >$PID_DUMP
110       # pattern to use for peeling off the process numbers.
111       local appropriate_pattern='s/^[-a-zA-Z_0-9][-a-zA-Z_0-9]*  *\([0-9][0-9]*\).*$/\1/p'
112       # remove the first line of the file, search for the pattern the
113       # user wants to find, and just pluck the process ids out of the
114       # results.
115       for i in "${patterns[@]}"; do
116         PIDS_SOUGHT+=($(cat $PID_DUMP \
117           | sed -e '1d' \
118           | grep -i "$i" \
119           | sed -n -e "$appropriate_pattern"))
120       done
121     fi
122     if [ ${#PIDS_SOUGHT[*]} -ne 0 ]; then
123       local PIDS_SOUGHT2=$(printf -- '%s\n' ${PIDS_SOUGHT[@]} | sort | uniq)
124       PIDS_SOUGHT=()
125       PIDS_SOUGHT=${PIDS_SOUGHT2[*]}
126       echo ${PIDS_SOUGHT[*]}
127     fi
128     /bin/rm $PID_DUMP
129   }
130   
131   # finds all processes matching the pattern specified and shows their full
132   # process listing (whereas psfind just lists process ids).
133   function psa() {
134     if [ -z "$1" ]; then
135       echo "psa finds processes by pattern, but there was no pattern on the command line."
136       return 1
137     fi
138     p=$(psfind "${@}")
139     if [ -z "$p" ]; then
140       # no matches.
141       return 0
142     fi
143     echo ""
144     echo "Processes matching ${@}..."
145     echo ""
146     if [ -n "$IS_DARWIN" ]; then
147       unset fuzil_sentinel
148       for i in $p; do
149         # only print the header the first time.
150         if [ -z "$fuzil_sentinel" ]; then
151           ps $i -w -u
152         else
153           ps $i -w -u | sed -e '1d'
154         fi
155         fuzil_sentinel=true
156       done
157     else 
158       # cases besides mac os x's darwin.
159       extra_flags=
160       if [ "$OS" = "Windows_NT" ]; then
161         # special case for windows.
162         extra_flags=-W
163         ps | head -1
164         for curr in $p; do
165           ps $extra_flags | grep "$curr" 
166         done
167       else
168         # normal OSes can handle a nice simple query.
169         ps wu $p
170       fi
171     fi
172   }
173   
174   # an unfortunately similarly named function to the above 'ps' as in process
175   # methods, but this 'ps' stands for postscript.  this takes a postscript file
176   # and converts it into pcl3 printer language and then ships it to the printer.
177   # this mostly makes sense for an environment where one's default printer is
178   # pcl.  if the input postscript causes ghostscript to bomb out, there has been
179   # some good success running ps2ps on the input file and using the cleaned
180   # postscript file for printing.
181   function ps2pcl2lpr() {
182     for $i in $*; do
183       gs -sDEVICE=pcl3 -sOutputFile=- -sPAPERSIZE=letter "$i" | lpr -l 
184     done
185   }
186   
187   function fix_alsa() {
188     sudo /etc/init.d/alsasound restart
189   }
190   
191   # switches from a /X/path form to an X:/ form.  this also processes cygwin paths.
192   function unix_to_dos_path() {
193     # we usually remove dos slashes in favor of forward slashes.
194     if [ ! -z "$SERIOUS_SLASH_TREATMENT" ]; then
195       # unless this flag is set, in which case we force dos slashes.
196       echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\/cygdrive//' | sed -e 's/\/\([a-zA-Z]\)\/\(.*\)/\1:\/\2/' | sed -e 's/\//\\/g'
197     else
198       echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\/cygdrive//' | sed -e 's/\/\([a-zA-Z]\)\/\(.*\)/\1:\/\2/'
199     fi
200   }
201   
202   # switches from an X:/ form to an /X/path form.
203   function dos_to_unix_path() {
204     # we always remove dos slashes in favor of forward slashes.
205     echo "$1" | sed -e 's/\\/\//g' | sed -e 's/\([a-zA-Z]\):\/\(.*\)/\/\1\/\2/'
206   }
207
208   # returns a successful value (0) if this system is debian or ubuntu.
209   function debian_like() {
210     # decide if we think this is debian or ubuntu or a variant.
211     DEBIAN_LIKE=$(if [ ! -z "$(grep -i debian /etc/issue)" \
212         -o ! -z "$(grep -i ubuntu /etc/issue)" ]; then echo 1; else echo 0; fi)
213     if [ $DEBIAN_LIKE -eq 1 ]; then
214       # success; this is debianish.
215       return 0
216     else
217       # this seems like some other OS.
218       return 1
219     fi
220   }
221   
222   # su function: makes su perform a login.
223   # for some OSes, this transfers the X authority information to the new login.
224   function su() {
225     if debian_like; then
226       # debian currently requires the full version which imports X authority
227       # information for su.
228   
229       # get the x authority info for our current user.
230       source $FEISTY_MEOW_SCRIPTS/x_win/get_x_auth.sh
231   
232       if [ -z "$X_auth_info" ]; then
233         # if there's no authentication info to pass along, we just do a normal su.
234         /bin/su -l $*
235       else
236         # under X, we update the new login's authority info with the previous
237         # user's info.
238         (unset XAUTHORITY; /bin/su -l $* -c "$X_auth_info ; export DISPLAY=$DISPLAY ; bash")
239       fi
240     else
241       # non-debian supposedly doesn't need the extra overhead any more.
242       # or at least suse doesn't, which is the other one we've tested on.
243       /bin/su -l $*
244     fi
245   
246     # relabel the console after returning.
247     bash $FEISTY_MEOW_SCRIPTS/tty/label_terminal_with_infos.sh
248   }
249   
250   # sudo function wraps the normal sudo by ensuring we replace the terminal
251   # label if they're doing an su with the sudo.
252   function sudo() {
253     local first_command="$1"
254     /usr/bin/sudo "$@"
255     if [ "$first_command" == "su" ]; then
256       # yep, they were doing an su, but they're back now.
257       bash $FEISTY_MEOW_SCRIPTS/tty/label_terminal_with_infos.sh
258     fi
259   }
260   
261   # trashes the .#blah files that cvs and svn leave behind when finding conflicts.
262   # this kind of assumes you've already checked them for any salient facts.
263   function clean_cvs_junk() {
264     for i in $*; do
265       find $i -follow -type f -iname ".#*" -exec perl $FEISTY_MEOW_SCRIPTS/files/safedel.pl {} ";" 
266     done
267   }
268
269   # overlay for nechung binary so that we can complain less grossly about it when it's missing.
270   function nechung() {
271     local wheres_nechung=$(which nechung 2>/dev/null)
272     if [ -z "$wheres_nechung" ]; then
273       echo "The nechung oracle program cannot be found.  You may want to consider"
274       echo "rebuilding the feisty meow applications with this command:"
275       echo "bash $FEISTY_MEOW_SCRIPTS/generator/bootstrap_build.sh"
276     else
277       $wheres_nechung
278     fi
279   }
280   
281   # recreates all the generated files that the feisty meow scripts use.
282   function regenerate() {
283     # do the bootstrapping process again.
284     echo "regenerating feisty meow script environment."
285     bash $FEISTY_MEOW_SCRIPTS/core/bootstrap_shells.sh
286     echo
287     # force a full reload by turning off sentinel variable and alias.
288     # the nethack one is used by fred's customizations.
289     # interesting note perhaps: found that the NETHACKOPTIONS variable was
290     # not being unset correctly when preceded by an alias.  split them up
291     # like they are now due to that bug.
292     unset -v FEISTY_MEOW_GENERATED NECHUNG NETHACKOPTIONS 
293     unset -f function_sentinel 
294     # reload feisty meow environment in current shell.
295     source $FEISTY_MEOW_SCRIPTS/core/launch_feisty_meow.sh
296     # run nechung oracle to give user a new fortune.
297     nechung
298   }
299
300   # generates a random password where the first parameter is the number of characters
301   # in the password (default 20) and the second parameter specifies whether to use
302   # special characters (1) or not (0).
303   # found function at http://legroom.net/2010/05/06/bash-random-password-generator
304   function random_password()
305   {
306     [ "$2" == "0" ] && CHAR="[:alnum:]" || CHAR="[:graph:]"
307     cat /dev/urandom | tr -cd "$CHAR" | head -c ${1:-32}
308     echo
309   }
310
311   # a wrapper for the which command that finds items on the path.  some OSes
312   # do not provide which, so we want to not be spewing errors when that
313   # happens.
314   function whichable()
315   {
316     to_find="$1"; shift
317     which which &>/dev/null
318     if [ $? -ne 0 ]; then
319       # there is no which command here.  we produce nothing due to this.
320       echo
321     fi
322     echo $(which $to_find)
323   }
324
325   # copies a set of custom scripts into the proper location for feisty meow
326   # to merge their functions and aliases with the standard set.
327   function recustomize()
328   {
329     user="$1"; shift
330     if [ -z "$user" ]; then
331       # use our default example user if there was no name provided.
332       user=fred
333     fi
334     if [ ! -d "$FEISTY_MEOW_DIR/customizing/$user" ]; then
335       echo "The customization folder provided for $user should be:"
336       echo "  '$FEISTY_MEOW_DIR/customizing/$user'"
337       echo "but that folder does not exist.  Skipping customization."
338       return 1
339     fi
340     regenerate >/dev/null
341     pushd "$FEISTY_MEOW_GENERATED/custom" &>/dev/null
342     local incongruous_files="$(bash "$FEISTY_MEOW_SCRIPTS/files/list_non_dupes.sh" "$FEISTY_MEOW_DIR/customizing/$user" "$FEISTY_MEOW_GENERATED/custom")"
343     if [ ${#incongruous_files} -ge 1 ]; then
344       echo "cleaning unknown older overrides..."
345       perl "$FEISTY_MEOW_SCRIPTS/files/safedel.pl" $incongruous_files
346       echo
347     fi
348     popd &>/dev/null
349     echo "copying custom overrides for $user"
350     mkdir "$FEISTY_MEOW_GENERATED/custom" 2>/dev/null
351     perl "$FEISTY_MEOW_SCRIPTS/text/cpdiff.pl" "$FEISTY_MEOW_DIR/customizing/$user" "$FEISTY_MEOW_GENERATED/custom"
352     if [ -d "$FEISTY_MEOW_DIR/customizing/$user/scripts" ]; then
353       echo "copying custom scripts for $user"
354       \cp -R "$FEISTY_MEOW_DIR/customizing/$user/scripts" "$FEISTY_MEOW_GENERATED/custom/"
355     fi
356     echo
357     regenerate
358   }
359
360   function add_cygwin_drive_mounts() {
361     for i in c d e f g h q z ; do
362       ln -s /cygdrive/$i $i
363     done
364   }
365
366
367   # takes a file to modify, and then it will replace any occurrences of the
368   # pattern provided as the second parameter with the text in the third
369   # parameter.
370   function replace_pattern_in_file()
371   {
372     local file="$1"; shift
373     local pattern="$1"; shift
374     local replacement="$1"; shift
375     if [ -z "$file" -o -z "$pattern" -o -z "$replacement" ]; then
376       echo "replace_pattern_in_file: needs a filename, a pattern to replace, and the"
377       echo "text to replace that pattern with."
378       return 1
379     fi
380     sed -i -e "s%$pattern%$replacement%g" "$file"
381   }
382
383   ##############
384
385   function function_sentinel() { return 0; }
386   
387   if [ ! -z "$SHELL_DEBUG" ]; then echo function definitions end....; fi
388   
389 fi
390