use input redirection
[myplc.git] / plc.d / functions
1 # -*-Shell-script-*-
2 #
3 # Common functions for PLC startup/shutdown scripts
4 #
5 # Mark Huang <mlhuang@cs.princeton.edu>
6 # Copyright (C) 2006 The Trustees of Princeton University
7 #
8 # $Id: functions,v 1.7 2007/01/19 17:12:45 mlhuang Exp $
9 #
10
11 export PATH=/sbin:/bin:/usr/bin:/usr/sbin
12
13 # Source function library
14 . /etc/init.d/functions
15
16 # Total number of errors
17 ERRORS=0
18
19 # Count the exit status of the last command
20 check ()
21 {
22     ERRORS=$(($ERRORS+$?))
23 }
24
25 # Print status header
26 dialog ()
27 {
28     echo -n "PLC: $*: " >&3
29 }
30
31 # Print result
32 result ()
33 {
34     if [ $ERRORS -eq 0 ] ; then
35         success "$*" >&3
36     else
37         failure "$*" >&3
38     fi
39     echo >&3
40 }
41
42 # Start up a program with a plc_ prefix
43 plc_daemon ()
44 {
45     base=${1##*/}
46
47     # See if it's already running. Look *only* at the pid file.
48     if [ -f /var/run/plc_${base}.pid ]; then
49         local line p
50         read line < /var/run/plc_${base}.pid
51         for p in $line ; do
52                 [ -z "${p//[0-9]/}" -a -d "/proc/$p" ] && pid="$pid $p"
53         done
54     fi
55
56     [ -n "${pid:-}" -a -z "${force:-}" ] && return
57
58     # And start it up.
59     (exec -a plc_${base} $*)
60     ret=$?
61
62     if [ -f /var/run/${base}.pid ] ; then
63         mv /var/run/${base}.pid /var/run/plc_${base}.pid
64     fi
65
66     return $ret
67 }
68
69 # Print IP address of hostname if resolvable
70 gethostbyname ()
71 {
72     perl -MSocket -e '($a,$b,$c,$d,@addrs) = gethostbyname($ARGV[0]); print inet_ntoa($addrs[0]) . "\n";' $1 2>/dev/null
73 }
74
75 # Forcefully make a symlink
76 symlink ()
77 {
78     mkdir -p $(dirname $2)
79     rm -f $2
80     ln -s $1 $2
81 }
82
83 # Argument(s) or stdin to lowercase stdout
84 lower ()
85 {
86     if [ ${#*} -ge 1 ] ; then
87         tr A-Z a-z <<<$*
88     else
89         tr A-Z a-z
90     fi
91 }
92
93 # Argument(s) or stdin to uppercase stdout
94 upper ()
95 {
96     if [ ${#*} -ge 1 ] ; then
97         tr a-z A-Z <<<$*
98     else
99         tr a-z A-Z
100     fi
101 }
102
103 # Make copies of stdout and stderr. The plc initscript redirects
104 # stdout and stderr to a logfile if -v is not specified.
105 [ ! -e /dev/fd/3 ] && exec 3>&1
106 [ ! -e /dev/fd/4 ] && exec 4>&2