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