summaryrefslogtreecommitdiffstats
path: root/sbin/init.d/functions
blob: 88ebbfc4325797ba1ad1534dd8a1d1b0deba5a8d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
#!/bin/bash

# not used ? ## DEBUG FILE
# not used ? #DEBUG=/tmp/.flx.$PID.$RANDOM
# not used ? #[ -e "$DEBUG" ] && rm -f $DEBUG && touch $DEBUG
# not used ? #if [ $? != 0 ] ; then DEBUG="" ; fi

# Test for previous sourcing already in progress
declare -F build_default_func > /dev/null && return

# SSHD starts this script with "-c" followed by all the parameters grouped into
# one single string. So we expand it to allow remote commands.
if [ "$1" = "-c" ]; then shift; set -- $*; fi

# Configuration file to use. Default : /etc/config.rc
export CONFIG=${CONFIG:-/etc/config.rc}

# Path to startup scripts. Default : /sbin/init.d
# INIT_PATH=${INIT_PATH:-/sbin/init.d}
INIT_PATH=${INIT_PATH:-`dirname $0`}

# Process name
PNAME=`basename $0`
PPATH=`dirname $0`
PFULLNAME=$0

# Global variable for status information. Set to "1" while processing the right
# section.
RUNNING_SECTION=

# goes "1" if at least one instance of the required service has been found
SVC_FOUND=

# no particular function defined yet
DEFINED_FUNCTIONS=

# not in list mode
MUST_LIST_SECTIONS=

# no option filter
OPTION_FILTER=

# signal to use at first when stopping a service. Default: TERM
# May be changed by any init script (eg: sshd)
STOP_FIRST_WITH=TERM

# set with --force to ignore current status
FORCE_START_STOP=0

# controls wether the service is being started with --auto
SVC_AUTO_START=0

# facility for syslog message
G_FACILITY=local3

# LOG FILE
LOGFILE=/var/log/startup.log
[ -L "$LOGFILE" ] && rm -f $LOGFILE

# the scripts can list some global variables which they use and that should be
# unset after processing the service. This is to be set globally.
SVC_VARS=

# this is set to $? for the first do_xxx which doesn't return 0
STATUS_RET=0

########################################
#           BASIC FUNCTIONS            #
########################################
function logit {
    # echo -n "'"
    # echo -n "$*" | sed -e "s/'/\\\\'/" -e "s//' '/g"
    # echo "'"
    echo "  $*"
    [ "${1##\#*}" -a "xG_FACILITY" != x ] && \
         logger -p $G_FACILITY.info -t "flxi[$$].$PNAME" -- \
           "exec[$USER]: $*"
    $*
    local return=$?
    [ $return != 0 -a "xG_FACILITY" != x ] && \
         logger -p $G_FACILITY.info -t "flxi[$$].$PNAME" -- \
           "exec.error[$USER]: $return"
    return $return
}

# returns the value for a given parameter in a config file. The value is both
# echoed and set to the REPLY variable.
# usage: valueof CONFIGFILE PARAMETER
function valueof {
    REPLY=$( awk 'BEGIN { FS="[:= \\t]+"} {gsub("#.*", "", $0); \
		if (match($1, "^'$2'$")) { \
		    gsub("^[:= \\t]*'$2'[:= \\t]+", "", $0); print $0 } }' $1 )
    echo $REPLY
}

# returns children processes ids.
# usage: getchild PID ...
function childrenpid {
    local found
    local pid=" $* "

    set -- $( exec ps ahxo ppid,pid ) ; while [ $# -gt 0 ] ; do 
	    [ -z "${pid/* $1 */}" ] && found="$found $2" ; shift ; shift ; done

    REPLY="" && [ "$found" ] && REPLY=$found && echo $REPLY
}


# Returns process id from process name only by looking at the process table.
# (ie: no pidfile used). Only processes which have ppid of 1 (or parent_pid)
# are returned. A list of pids to omit can be specified with "-o".
# If no process name is specified, all the parent's children are returned.
# svc_pidof [ -o "omit_pids*" ]* [ -p parent_pid ] [ PNAME ... ]
function svc_pidof {
    local omit=x
    local ppid=1
    local comm
    local found

    while [ $# -gt 0 ] ; do
	if [ "x$1" = "x-o" ] ; then omit="$omit ${2/%PPID/$$} " ; shift 2
	elif [ "x$1" = "x-p" ] ; then ppid="$2" ; shift 2
	else comm="$comm $1 " ; shift 1
	fi
    done

    #set -- "$( exec ps ahxo pid,ppid,comm )" ; set -- $( echo "$1" | awk '{ print $1,$2,$3}' )
    set -- $( ps ahxo pid,ppid,comm | awk '{ print $1,$2,$3}' )
    while [ $# -gt 0 ] ; do 
	[ -z "${comm/* $3 */}" -a -n "${omit/* $1 */}" -a "$2" = "$ppid" ] && found="$found $1" 
	shift ; shift ; shift
    done
    REPLY="" && [ "$found" ] && REPLY=$found && echo $REPLY
}

########################################
# CONFIGURATION FILE LOADING FUNCTIONS #
########################################

# All functions handling options get the option name as a first argument,
# then the rest of the line follows.

# default function for config directive. This one is called only for unmapped
# options, so either bad ones or unused services.
function default_config_option {
    [ "$RUNNING_SECTION" ] && echo "Bad option '$1' in '$*'"
}

# builtin function to create a variable from an option.
# The variable name is "opt_$option" where option is the option name.
function standard_option {
    if [ "x$2" = "x--disable" ]; then
	eval "opt_$1="
    else
	eval "opt_$1='$2'"
    fi
}

# builtin function to create a variable from an option.
# The variable name is "opt_$option" where option is the option name.
function boolean_option {
    if [ "x$2" = "x--disable" ]; then
	eval "opt_$1=0"
    else
	eval "opt_$1=1"
    fi
}

# builtin function to create a variable from an option.
# The variable name is the same as the option name.
# This is mainly used for reserved options such as "bin" and "cmdline",
# or to port older startup scripts.
# The option value is NOT evaluated now, which means that cmdline can refer to
# $bin if properly quoted. Eg: cmdline '$bin -f $config'
function reserved_option {
    if [ "x$2" = "x--disable" ]; then
	eval "$1="
    else
	eval "$1='$2'"
    fi
}

# builtin function to create a variable from an option.
# The variable name is "opt_$option" where option is the option name.
function long_option {
    if [ "x$2" = "x--disable" ]; then
	eval "opt_$1="
    else
	local optname=$1
	shift
	eval "opt_$optname='$*'"
    fi
}

# builtin function to create an array from an option.
# The variable name is "opt_$option" where option is the option name.
# The array is extended with all the args for each occurence of the option.
# If no arg is given, the option is extended with a single dash '#' so that
# we further know that it has been called.
function multiple_option {
    if [ "x$2" = "x--disable" ]; then
	# in case of multiple_option, "no <option> <args>" only
	# means that we don't want to add <args> to <option>,
	# but not that we want to clear <option>
	# eval "opt_$1=( )"
	:
    else
	local optname=$1
	shift
	if [ $# -gt 0 ]; then
	    #eval "opt_$optname=( \$opt_$optname \"$*\" )"
	    eval "opt_$optname[\${#opt_$optname[*]}]='$*'"
	else
	    # if no option is set, this reference will be lost because in fact
	    # it will be added as an empty entry in the list. So we replace it
	    # with a dash '#' to mark it as referenced.
	    eval "opt_$optname[\${#opt_$optname[*]}]='#'"
	fi
    fi
}

# not used ? ## backup all defined functions
# not used ? #function backup_func {
# not used ? #	BACKUP_FUNC="$( declare -f | sed 's/^declare -f /function /' )"
# not used ? #}
# not used ? #
# not used ? ## restore all previous defined functions
# not used ? #function restore_func {
# not used ? #	# remove all defined functions
# not used ? #	for func in $( declare -F | sed 's/^declare -f //') ; do unset -f $func ; done
# not used ? #	eval "$BACKUP_FUNC"
# not used ? #}
# not used ? #
# not used ? ## backup variable with value
# not used ? #function backup_set {
# not used ? #	BACKUP_SET="$( set | grep "^[a-zA-Z_][a-zA-Z0-9_]*=[^(]" )"
# not used ? #}
# not used ? #
# not used ? ## restore original values to variables
# not used ? #function restore_set {
# not used ? #	unset -v $( set | grep "^[a-zA-Z_][a-zA-Z0-9_]*=[^(]" | cut -f1 -d= )
# not used ? #	eval "$BACKUP_SET"
# not used ? #}
# not used ? #

# not used ? ## 'need_svc' function start needed service and wait a valid return
# not used ? #function need_svc {
# not used ? #	local p=$1
# not used ? #	if [ -x $INIT_PATH/$p ] ; then
# not used ? #	  ( $INIT_PATH/$p $ACTION ) &
# not used ? #	  while [ -L /proc/$!/cwd ] ; do
# not used ? #	    echo "Waiting for $p to $ACTION ..."
# not used ? #	  done
# not used ? #	fi
# not used ? #	return 0
# not used ? #}
# not used ? #
# not used ? ## 'try_svc' function start needed service before running
# not used ? #function try_svc {
# not used ? #	return 0
# not used ? #}
# not used ? #
# not used ? ## check configuration and re-set arguments that do not work
# not used ? #function set_config {
# not used ? #	declare -F check_config >/dev/null || return 0
# not used ? #	check_config | while read ; do
# not used ? #	  set -- $REPLY
# not used ? #	  if [ "$1" = "KO:" ] ; then
# not used ? #	    shift 
# not used ? #	    logit $*
# not used ? #	  fi
# not used ? #	done
# not used ? #}

# unusable for several instances ## 'replace' function to reassign
# unusable for several instances ## if replace first parameter is '-', do not repeat orginal func
# unusable for several instances ## name as first parameter of the replacement function
# unusable for several instances #function replace {
# unusable for several instances #    [ "$RUNNING" != 1 ] && return
# unusable for several instances #    if [ "x$1" = "x-" ] ; then
# unusable for several instances #	  shift
# unusable for several instances #	  eval "function do_$1 { $2 \$* ; }"
# unusable for several instances #    else
# unusable for several instances #	  eval "function do_$1 { $2 $1 \$* ; }"
# unusable for several instances #    fi
# unusable for several instances #}

# default start function
# usage : do_start process_name [instance_name]
# if functions fct_pre_start() and fct_post_start() are defined, they will be
# called just before and just after the cmdline.
function do_start {
    local p=$1
    local instname=$2
    local ret
    do_status $p $instname > /dev/null 2>&1
    if [ $? = 0  -a $FORCE_START_STOP -eq 0 ] ; then
	echo "Process $p${instname:+[$instname]} already running."
	[ $SVC_AUTO_START -eq 0 ] && echo "  ==> please use '--force' or 'restart' instead or check with 'status'."
	return 0
    fi

    echo "# Starting $p${instname:+[$instname]} ..."
    declare -F fct_pre_start >/dev/null && fct_pre_start $p $instname
    logit $cmdline
    ret=$?
    declare -F fct_post_start >/dev/null && fct_post_start $p $instname
    [ $ret -eq 0 ] && echo "  ==> start $p${instname:+[$instname]} Done." || \
		    { echo "  ==> start $p${instname:+[$instname]} Failed." ; return 1 ; }
    return 0
}

#
# This function tries to stop the process whose pid is specified in the file
# in $1. It returns 0 if the process is stopped, or 1 if it is still running.
# There can be only one pid per pidfile.
#
# usage : do_stop_with_pidfile pidfile [process_name [instance_name]]
# if functions fct_pre_stop() and fct_post_stop() are defined, they will be
# called just before and just after a successful kill sequence.
function do_stop_with_pidfile {
    local pid
    local pids
    local pidfile=$1
    local pname=$2
    local instname=$3

    svc_pidof -o $$ $pname > /dev/null ; pids=$REPLY
    
    if [ $FORCE_START_STOP -eq 0 ]; then
	if ! [ -r "$pidfile" ] || ! read pid REPLY <"$pidfile" || ! [ -L /proc/$pid/cwd ]; then
	    echo "# Process $pname${instname:+[$instname]} already stopped (according to $pidfile)${pids:+, but check pids : $pids}"
	    return 0
	fi
    fi

    valueof /proc/$pid/status Name >/dev/null ; set -- $REPLY
    if [ "$pname" -a "x$pname" != "x$1" -a $FORCE_START_STOP -eq 0 ]; then
	echo "# The pid in $pidfile points to a wrong process name ($pid:$1)${pids:+. Check $pids for $pname${instname:+[$instname]}}."
	return 1;
    fi
 
    echo "# Stopping $pname${instname:+[$instname]} (pid $pid according to $pidfile) ..."
    declare -F fct_pre_stop >/dev/null && fct_pre_stop $pname $instname
    kill -CONT $pid; kill -$STOP_FIRST_WITH $pid ; set -- 0 1 2 3
    while [ -L /proc/$pid/cwd -a $# -gt 0 ] ; do sleep $1 ; shift ; done
    [ -L /proc/$pid/cwd ] && { kill -9 $pid ; sleep 1 ; }
    [ -L /proc/$pid/cwd ] && { echo "  ==> stop $pname${instname:+[$instname]} Failed." ; return 1; }
    if [ -e "$pidfile" ]; then rm -f "$pidfile"; fi
    declare -F fct_post_stop >/dev/null && fct_post_stop $pname $instname
    echo "  ==> stop $pname${instname:+[$instname]} Done."
    return 0
}

#
# default stop function
# If a pidfile exists, it is used. Otherwise, all pids with same name which have
# init for parent will be killed.
# The function returns 0 if the process is(are) stopped, and 1 if not all could
# be stopped.
#
# usage : do_stop process_name [instance_name]
# if functions fct_pre_stop() and fct_post_stop() are defined, they will be
# called just before and just after a successful kill sequence.
function do_stop {
    local pname=$1
    local instname=$2
    local pid
    local retry
    shift
 
    pname=${procname:-$pname}
    # stop service from pidfile 
    [ "x$pidfile" != x ] && { do_stop_with_pidfile $pidfile $pname $instname; return $? ; }

    # stop service from pidof data
    svc_pidof -o $$ $pname > /dev/null
    if [ -z "$REPLY" ]; then
	echo "# Process $pname${instname:+[$instname]} already stopped, cleaning up..."
	declare -F fct_post_stop >/dev/null && fct_post_stop $pname $instname
	echo "  ==> stop $pname${instname:+[$instname]} Done."
	return 0
    fi
    echo "# Stopping process $pname${instname:+[$instname]} (pids : $REPLY) ..."
    retry=$REPLY; # save it temporarily
    declare -F fct_pre_stop >/dev/null && fct_pre_stop $pname $instname
    REPLY=$retry; retry=0
    while [ "$REPLY" ]; do
	retry=$[$retry+1]
	if [ $retry -le 3 ]; then kill -CONT $REPLY && kill -$STOP_FIRST_WITH $REPLY || break; sleep $retry
	elif [ $retry -gt 3 ]; then kill -9 $REPLY || break; sleep 1
	else break; fi
	REPLY=`ps ho pid $REPLY`
    done
    if [ "$REPLY" ]; then
	echo "  ==> stop $pname${instname:+[$instname]} Failed. (pids : $REPLY)"
	return 1
    else
	declare -F fct_post_stop >/dev/null && fct_post_stop $pname $instname
	echo "  ==> stop $pname${instname:+[$instname]} Done."
	return 0
    fi
}

function do_restart {
    do_stop $*
    do_start $*
}

# returns a basic check of the service, an returns one line of info of the form:
# <hostname> <service_name>.[instance_name] <date_in_secs>  {RUNNING|STOPPED}[,more_info] [{OK|CONFIG_CHANGED}]
# returns 0 if running.
function do_check {
    local run_stat
    local status=OK
    local ret uptime=0
    local pid

    do_status $1 $2 > /dev/null
    ret=$?
    if [ $ret -eq 0 ]; then
	if [ "$REPLY" ]; then
	    for pid in $REPLY; do
		uptime=$[$(date +%s)-$(date -d "`ps ho lstart $pid`" +%s)]
		echo "`uname -n` $1.$2 `date +%s` RUNNING $uptime $status"
	    done
	else
	    echo "`uname -n` $1.$2 `date +%s` RUNNING 0 $status"
	fi
    else
        run_stat=STOPPED
	case $ret in
	    1)  status=ALERT,nofile ;;
	    2)  status=ALERT,nopid  ;;
	    3)  status=ALERT,other  ;;
	    *)  status=ALERT        ;;
	esac
	echo "`uname -n` $1.$2 `date +%s` $run_stat $uptime $status"
    fi
    return $ret
}

# returns 0 if the process is running, 1 if the pid file does not exist,
# 2 if the pid doesn't exist anymore, 3 if it has been affected to another
# process name. If the process is running, REPLY is set to its pid.
# usage : do_status_with_pidfile pidfile [process_name [instance_name]]
function do_status_with_pidfile {
    local pidfile=$1
    local pname=$2
    local instname=$3
    local pid

    [ -r "$pidfile" ] || { echo "Process $pname${instname:+[$instname]} stopped (no pidfile present)" ; return 1 ; }
    read pid < $pidfile
    [ -L /proc/$pid/cwd ] || { echo "Process $pname${instname:+[$instname]} stopped (from pidfile)" ; return 2 ; }
    valueof /proc/$pid/status Name >/dev/null ; set -- $REPLY
    [ "$pname" -a "x$pname" = "x$1" ] || {
	echo "Process with an other name ($1,$pid) already running."
	echo "  ==> you should remove invalid pidfile $pidfile"
	return 3
    }
    childrenpid $pid > /dev/null
    local cpid=$*
    echo "Process $pname${instname:+[$instname]} running : $pid ${cpid:+($cpid)}"
    REPLY=$pid
    return 0
}

# returns 0 if the process is running; 1 if it's stopped and there's no pid file,
# otherwise same as do_status_with_pidfile(). If the process is running, REPLY is
# set to its pid.
# usage : do_status process_name [instance_name]
function do_status {
    local pname=$1
    local instname=$2
    shift

    pname=${procname:-$pname}
    # get info from pidfile if it exist 
    [ "x$pidfile" != x ] && { do_status_with_pidfile $pidfile $pname $instname; return $? ; }
    
    # get info from pidof command
    svc_pidof -o $$ $pname > /dev/null ; pids=$REPLY
    [ "$pids" ] && { echo "Process $pname${instname:+[$instname]} running without pidfile : $pids" ; return 0 ; }
    echo "Process $pname${instname:+[$instname]} stopped (no pidfile used)."
    return 1
}

# lists all the known options for the current service, with their default or
# assigned values. There is a double eval so that options depending on others
# are correctly resolved.
# The output format is "process_name.[instance_name] option value"
# usage : list_options process_name [instance_name]
function do_list_options {
    local i=0
    local occur=0
    local nbocc=0
    local inst="$1.$2"

    while [ $i -lt $svc_nbopts ]; do
	if [ -z "$OPTION_FILTER" -o "$OPTION_FILTER" = "${svc_opts[$i]}" ]; then


	    if [ "${svc_fcts[$i]}" = "boolean_option" -o \
		 "${svc_fcts[$i]}" = "standard_option" -o \
		 "${svc_fcts[$i]}" = "long_option" -o \
		 "${svc_fcts[$i]}" = "reserved_option" ]; then
		    eval eval echo $inst ${svc_opts[$i]} \$"${svc_vars[$i]}"
	    elif [ "${svc_fcts[$i]}" = "multiple_option" ]; then
		eval nbocc='${#'"${svc_vars[$i]}"'[*]}'
		if [ $nbocc -eq 0 ]; then # no value, let's at least show the option name
		    eval echo $inst ${svc_opts[$i]}
		else
		    while [ $occur -lt $nbocc ]; do
			eval eval echo $inst ${svc_opts[$i]} '${'"${svc_vars[$i]}"'[$occur]}'
			occur=$[$occur+1]
		    done
		fi
	    else
		echo $inst ${svc_opts[$i]} "[defined by script]"
	    fi
	fi
	i=$[$i+1]
    done
}

# maps an option to a function. Existing options are simply overridden.
# usage: option option_name function_name [ defaults ]
function option {
    local name=$1
    local fct=$2
    local def=$3
    local opt=0

    # first, check if this option has already been defined, and return its
    # index, or a new one if it's new.
    while : ; do
	if [ $opt -ge $svc_nbopts ]; then svc_nbopts=$[$opt+1]; break; fi
	if [ "x$name" = "x${svc_opts[$opt]}" ]; then break; fi
	opt=$[$opt+1]
    done

    svc_opts[$opt]=$name
    svc_fcts[$opt]=$fct
    svc_defs[$opt]=$def
    if [ "x$fct" = "xboolean_option" -o "x$fct" = "xstandard_option" -o \
	 "x$fct" = "xlong_option" -o "x$fct" = "xmultiple_option" ]; then
	svc_vars[$opt]=opt_$name
    elif [ "x$fct" = "xreserved_option" ]; then
	svc_vars[$opt]=$name
    else
	svc_vars[$opt]=""
    fi

    #eval "function $1 { $2 $1 \$* ; }"
}

# This function is called once at load time. It scans the config file for all
# referenced options, and assigns them to a quiet function which yells only
# an unknown option has been referenced in a requested section. The options are
# discovered by reading all the first words.
#
# usage: build_default_func config_file
function build_default_func {
    local file=$1
    [ -f $file ] || return 1 
    # undefine all previously defined functions
    for func in $DEFINED_FUNCTIONS ; do unset -f $func ; done
    DEFINED_FUNCTIONS=`awk '{gsub("#.*", "", $1); \
                           if (match($1, "^[a-zA-Z0-9][a-zA-Z0-9_]*$")) \
                           print $1 | "sort -u" }' $file `
    # get all first words and build a default function
    for i in $DEFINED_FUNCTIONS ; do
	# language exceptions should be here if really needed
	# [ "$i" = "no" ] && continue;
	# [ "$i" = "service" ] && continue;
	# [ "$i" = "section" ] && continue;
	# [ "$i" = "interface" ] && continue;
	[ "$i" = "replace" ] && continue;
	# [ "$i" = "try_svc" ] && continue;
	# [ "$i" = "need_svc" ] && continue;
	if ! eval "declare -F $i > /dev/null" ; then 
	    eval "function $i { default_config_option $i \$* ; } "
	fi 
    done
}

# default 'service' function.
# Called as default_service svc_name [svc_instance] from load_config.
# SVC_ARGS is set from the service command line, and is used at next one.
function default_service {
    local ret
    local opt
    local val
    # skip first parameter (probably 'service')
    #shift  

    # we're in listing mode, we do nothing except listing the services
    if [ "$MUST_LIST_SECTIONS" = 1 -a $# -ge 1 ]; then
	[ "$1" != "${SVC_ARGS[0]}" -o "$2" != "${SVC_ARGS[1]}" ] && echo $*
	SVC_ARGS=( $* )
	return
    fi

    # check for running selected service
    if [ "$RUNNING_SECTION" = 1 ]; then
	# first, we'll check wether the next service is *exactly* the same as
	# the current one, in which case they are merged, in order to avoid
	# duplicate starts (system for example)
	if [ "$PNAME" = "$1" -a "${SVC_ARGS[0]}" = "$2" ]; then
	    return
	fi

	# try to insert command-line options
	while [ "$FORCE_OPTIONS" ]; do  # "opt=val,opt=val..."
	    opt=${FORCE_OPTIONS%%,*}
	    val=${opt#*=}
	    opt=${opt%%=*}
	    eval $opt $val
	    if [ "${FORCE_OPTIONS%%*,*}" ]; then # no more ','
		break;
	    else
		FORCE_OPTIONS=${FORCE_OPTIONS#*,}
	    fi
	done

	# unset all options to avoid conflicts with commands (eg: modprobe, ip ...)
	for i in ${svc_opts[*]} ; do
	    unset -f $i
	done

	# force a last eval on each reserved option so that they can refer to
	# each other.
	for i in bin pidfile procname cmdline; do eval eval "$i=\\\"\$$i\\\""; done

	# now if the script defines a fct_end_section() function, let's call
	# it to fix some values, or extract som from external config files.
	declare -F fct_end_section > /dev/null && fct_end_section $PNAME ${SVC_ARGS[*]}

	if [ "$SVC_AUTO_START" = 0 -o "$autostart" = 1 ]; then
	    do_$ACTION $PNAME ${SVC_ARGS[*]}
	fi
	ret=$?
	if [ $ret -gt 0 ]; then
	    STATUS_RET=$ret
	fi
        if [ "x$G_FACILITY" != x ] ; then
          if [ "x$ACTION" = xstart -o "x$ACTION" = xstop \
               -o "x$ACTION" = xrestart ] ; then 
            if [ $ret -gt 0 ] ; then
              logger -p $G_FACILITY.err -t flxi[$$].$PNAME -- \
                  "error[$USER]: $PNAME $ACTION ${SVC_INSTANCE[*]} = $ret"
            else
              logger -p $G_FACILITY.info -t flxi[$$].$PNAME -- \
                  "done[$USER]: $PNAME $ACTION ${SVC_INSTANCE[*]}"
            fi 
          fi
        fi
	unset -v RUNNING_SECTION SVC_ARGS bin cmdline pidfile procname $SVC_VARS

	# reset all options to the default option
	for i in ${svc_opts[*]} ; do
	    eval "function $i { default_config_option $i \$* ; } "
	done
    fi

    # if service is the one wished, start it at the end
    if test "x$1" = "x$PNAME" -a \
	    \( "x$2" = "x${SVC_INSTANCE[0]}" -o "x${SVC_INSTANCE[0]}" = "x" \) ; then
	# we can test difference between SVC_ARGS and SVC_INSTANCE
	SVC_FOUND=1
	RUNNING_SECTION=1
	shift
	SVC_ARGS=( $* )

	# reset every variable
	unset -v ${svc_vars[*]}

	# map all options to their functions, and set default vars.
	i=0
	while [ $i -lt $svc_nbopts ]; do
	    eval "function ${svc_opts[$i]} { ${svc_fcts[$i]} ${svc_opts[$i]} \$* ; } "
	    if [ "${svc_vars[$i]}" ]; then
		if [ "x${svc_fcts[$i]}" != "xmultiple_option" ]; then
		    eval "${svc_vars[$i]}='${svc_defs[$i]}'"
		else
		    eval "${svc_vars[$i]}=( )"
		fi
	    fi
	    i=$[$i+1]
	done

	# now if the script defines a fct_begin_section() function, let's call
	# it to preset some default values from external config files.
	unset -v $SVC_VARS
	declare -F fct_begin_section > /dev/null && fct_begin_section $PNAME ${SVC_ARGS[*]}
    fi
}

# 'no' for 'no ... ', disable a service or an option
function default_no {
    local req=$1
    shift
    case "$req" in
	"service")
	    default_service
	    ;;
	"section")
	    default_service
	    ;;
        "interface")
	    default_service
	    ;;
	*)
	    if [ "$MUST_LIST_SECTIONS" = 1 ]; then
		return
	    fi
	    local opt=0
	    while : ; do
	    	if [ $opt -ge $svc_nbopts ]; then
		    # non error since we don't know if this is a valid word.
	    	    return
	    	fi
	    	if [ "x$req" = "x${svc_opts[$opt]}" ]; then
	    	    if [ "x${svc_fcts[$opt]}" != "xmultiple_option" ]; then
			eval "${svc_vars[$opt]}=''"
	    	    else
			# in case of multiple_option, "no <option> <args>" only
			# means that we don't want to add <args> to <option>,
			# but not that we want to clear <option>
	    		# eval "${svc_vars[$opt]}=( )"
			:
	    	    fi
	    	    break
	    	fi
	    	opt=$[$opt+1]
	    done

	    # this doesn't work because $req is launched under a subshell !
	    #if declare -F $req >/dev/null; then
	    #    eval "$req --disable $*"
	    #fi
    esac
}

# source configuration file, called last.
function load_config {
    # defines functions for all first words in the config file
    build_default_func $CONFIG

    # defines functions for reserved keywords: no, service, section, interface.
    function no { default_no $*; }
    function service { default_service $*; }
    function section { default_service $*; }
    function interface {
	if [ "$PNAME" = "network" ]; then
	    echo "Warning: use of 'interface $1' keyword is deprecated. Use 'section network $1' instead.";
	fi
	default_service network $*;
    }

    if test ! -d "$CONFIG" -a -e "$CONFIG" ; then 
	# first keywords out of a section space are for the system, so let's enter
	# automatically in system section.
	service system
	. $CONFIG
	service ""
    fi

    if [ "$SVC_FOUND" != 1 -a "$MUST_LIST_SECTIONS" != 1 ]; then
	echo "Service/instance not found in $CONFIG, using default values."
	service $PNAME ; service ""

        #[ "x$G_FACILITY" != x ] && \
        #   logger -p $G_FACILITY.warn -t "flxi[$$].$PNAME" -- \
        #     "unknown[$USER]: $PNAME $ACTION ${SVC_INSTANCE[*]}"
	exit 1
    fi
    return $STATUS_RET
}

##################################
#   ALWAYS LOADED WHEN SOURCED   #
##################################
# build default undefined functions

svc_opts=( )
svc_vars=( )
svc_defs=( )
svc_fcts=( )
svc_nbopts=0

while [ $# -gt 0 ] ; do
    case "$1" in
    -f|--file)	# use this configuration file
	export CONFIG=$2
	shift 2
	;;
    --auto)	# only start services which don't have a "no autostart" statement
	SVC_AUTO_START=1
	shift 1
	;;
    --force)	# force start or stop disregarding current status
	FORCE_START_STOP=1
	shift 1
	;;
    --list_sections)	# list all known sections
	MUST_LIST_SECTIONS=1
	load_config
	exit 0
	;;
    --filter_option)	# display only this option in list_options
	OPTION_FILTER=$2
	shift 2
	;;
   -o|--option)		# force options : -o "opt=val,opt=val..."
	FORCE_OPTIONS=$2
	shift 2
	;;
    -*)
	echo "Global options :"
	grep $'^[ \t]*-[-a-z0-9_|]*)[ \t]*# ' $PPATH/functions | \
	    sed -e $'s/^\\([ \t]*\\)\\([^)]*\\)\\([ \t#)]*\\)\\(.*\\)/    \\2\t\t\\4/'
	echo "Other options :"
	declare -F usage > /dev/null && usage $* || \
	    echo "    -h|--help		display this help" && \
		[ "x$USAGE" != x ] && echo "$USAGE"
	exit 1
	;;
    *)
	break 
	;;
    esac
done

# Assign the requested action to ACTION (first arg). Default : start
ACTION=${1:-start}; shift

# Assign the requested instances to SVC_INSTANCE. Default : ""
SVC_INSTANCE=( $* )

# most services don't need to redefine the keywords "bin", "cmdline",
# "pidfile", "procname" and "check_interval", so let's initialize them now.
# This also means that any service can use these options without declaring them.
option	bin		reserved_option
option	cmdline		reserved_option '$bin'
option	pidfile		reserved_option
option	procname	reserved_option
option	check_interval	reserved_option	0
option	autostart	reserved_option	1

return 0

######### end of script, here comes some documentation #########

When a service is started, these operations are performed for each section
containing the same name, and the same instance name if any, or any instance if
no name is set :

  - options variables are initialized to their default values
  - if fct_begin_section() exists, it is called with service name and instance name
  - options are interpreted
  - bin,pidfile,cmdline,procname are converted through an eval so that they can
    reference variables options with '$name' or '$opt_name'.
  - if fct_end_section() exists, it is called with service name and instance name
  - if do_start() exists, it is called with service name and instance name.
    Otherwise, the default do_start() function is called with same args. This
    function calls fct_pre_start() with same args if it exists, just before
    starting $cmdline, and then fct_post_start() just after.

In case of a stop, everything is the same except do_start() which is replaced
with do_stop(). This last one also calls fct_pre_stop() and fct_post_stop(),
but this last one only if the stop is successful.

If the service is started as "service --auto start", the option "autostart" is
checked, and if set to 0, the service will not start. This is useful to
differentiate between configured services and enabled services.