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