summaryrefslogtreecommitdiff
path: root/runvdr
blob: 4959ae73d51906d864680065ec9d53b0c5c68cef (plain)
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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
#!/bin/bash
#
#  runvdr extreme - configurable vdr launcher script
#
#  Copyright (C) 2006-2009 Udo Richter
#                2013      Manuel Reimer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# Or, point your browser to http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
#
# The authors can be reached at <udo_richter(a)gmx.de>
#                               <manuel.reimer@gmx.de>
#
# The project's page is at
# http://projects.vdr-developer.org/projects/runvdr-extreme


RUNVDR="${0##*/}"
RUNVDRCONF=""


# Some unix commands being used:

PGREP="pgrep"
PS="ps"
GETOPT="getopt"
SLEEP="sleep"
CHVT="chvt"
DATE="date"

# Options summary and conf file entries of runvdr:
#
# -C # --runvdr-conf=#   RUNVDRCONF       location of runvdr config file
# --                     ADDPARAMS        Additional parameters to pass to VDR
# --pluginsetup-conf=#   PLUGINSETUPCONF  location of plugin-setup-runvdr.conf
# --setupplugin-conf=#   SETUPPLUGINCONF  location of setup-plugin sysconfig
# --vdr=#                VDRPRG           location and name of the vdr binary
# --switchterminal=#     SWITCHTERMINAL   console terminal to switch to
# --xserver=#            XSERVER          start X server for VDR
# --xserver-proxy=#                       runvdr internal use only
# --runvdr-pid=#         RUNVDRPID        location of runvdr.pid file
# --dvb-load=#           DVBLOAD          command to load DVB drivers
# --dvb-unload=#         DVBUNLOAD        command to unload DVB drivers
# --dvb-unload-on-exit   DVBUNLOADONEXIT  do unload DVB drivers on exit
# --x-startup=#          XSTARTUP         command executed after X startup
# --x-shutdown=#         XSHUTDOWN        command executed before X shutdown
# --wrapper=#            WRAPPER          wrapper command for calling vdr
# --terminate[=#]        TERMINATE        Terminate runvdr by pid
# --wait[=#]             WAIT             Wait # seconds for --terminate to finish
# --restart[=#]          RESTART          Send restart signal by pid
# --dvb-restart[=#]      DVBRESTART       Send dvb-restart signal by pid
# --term-timeout=#       TERMTIMEOUT      Timeout for VDR to react on SIGTERM
# --kill-timeout=#       KILLTIMEOUT      Timeout for VDR to react on SIGKILL
# --maxrestarts=#        MAXRESTARTS      Max number of rapid restarts before give-up
# --restarttime=#        RESTARTTIME      Max time for restart to be rapid
# --language=#           LANGUAGE         Locale to set for VDR
# --charset-override=#   VDR_CHARSET_OVERRIDE Override VDR charset
# -V --version           VERSION          print version information and exit
# -h --help              HELP             print this help and exit
#
# Supported options of VDR
#
#  -a #  --audio #     AUDIO            send Dolby Digital audio to stdin of command #
#        --cachedir=#  CACHEDIR         save cache files in DIR
#  -c #  --config #    CONFIGDIR        read config files from DIR
#  -d    --daemon      DAEMON           run in daemon mode
#  -D #  --device #    DVBDEVICE        use only the given DVB device (NUM = 0, 1, 2...)
#        --dirnames=#  DIRNAMES         Changes recording directory name format
#  -E #  --epgfile #   EPGFILE          write the EPG data into the given FILE. - to disable.
#  -g #  --grab #      GRAB             write images from the SVDRP command GRAB into the given DIR;
#  -L #  --lib #       LIBDIR           search for plugins in DIR (default is %s)
#        --lirc #?     LIRC             use a LIRC remote control device, attached to PATH
#        --localedir # LOCALEDIR        search for locale files in DIR
#  -i #  --instance #  INSTANCE         use ID as the id of this VDR instance
#  -l #  --log #       LOGLEVEL         set log level (default: 3)
#  -m    --mute        MUTE             mute audio of the primary DVB device at startup
#        --no-kbd      NOKBD            don't use the keyboard as an input device
#  -P #  --plugin #    PLUGINS          load a plugin defined by the given options
#  -p #  --port #      SVDRPPORT        use PORT for SVDRP
#        --rcu #?      RCU              use a remote control device, attached to PATH
#  -r #  --record #    RECORDCMD        call CMD before and after a recording
#        --resdir=#    RESDIR           read resource files from DIR
#  -s #  --shutdown #  SHUTDOWN         call CMD to shutdown the computer
#  -t #  --terminal #  TERMINAL         controlling tty
#  -u #  --user #      USER             run as user USER; only applicable if started as root
#        --userdump    USERDUMP         allow coredumps if -u is given (debugging)
#        --vfat        VFAT             encode special characters in recording names
#  -v #  --video #     VIDEODIR         use DIR as video directory
#  -w #  --watchdog #  WATCHDOG         activate the watchdog timer with a timeout of SEC


which $PGREP     >/dev/null || { echo missing $PGREP... >&2 ;   exit 1 ; }
which $PS        >/dev/null || { echo missing $PS... >&2 ;      exit 1 ; }
which $GETOPT    >/dev/null || { echo missing $GETOPT... >&2 ;  exit 1 ; }
which $SLEEP     >/dev/null || { echo missing $SLEEP... >&2 ;   exit 1 ; }
which $CHVT      >/dev/null || { echo missing $CHVT... >&2 ;    exit 1 ; }
which $DATE      >/dev/null || { echo missing $DATE... >&2 ;    exit 1 ; }



function ParseCommandLine_Step1() {
    # Parse command line, step 1
    # Stores pre-processed options in $OPTIONS
    # evaluates -C, --runvdr-conf and --xserver-proxy only

    SHORTOPT="a:c:C:dD:E:g:hi:l:L:mp:P:r:s:t:u:v:Vw:"
    LONGOPT="runvdr-conf:,xserver-proxy:,pluginsetup-conf:,setupplugin-conf:,vdr:,\
        switchterminal:,maxrestarts:,restarttime:,xserver:,\
        runvdr-pid:,dvb-load:,dvb-unload:,dvb-unload-on-exit,x-startup:,\
        x-shutdown:,language:,charset-override:,wrapper:,\
        term-timeout:,kill-timeout:,terminate::,restart::,dvb-restart::,\
        wait::,audio:,cachedir:,config:,daemon,device:,dirnames:,epgfile:,grab:,help,lib:,lirc::,\
        instance:,log:,localedir:,mute,no-kbd,plugin:,port:,rcu::,record:,resdir:,shutdown:,\
        terminal:,user:,userdump,version,vfat,video:,watchdog:"

    # prepare all optios for later processing
    OPTIONS=`$GETOPT -o "$SHORTOPT" --long "$LONGOPT" -n "$0" -- "$@"` || exit 1

    eval set -- "$OPTIONS"

    XSERVERPROXY=
    while true ; do case "$1" in
        -C|--runvdr-conf)  RUNVDRCONF="$2";  shift 2;;
           --xserver-proxy) XSERVERPROXY="$2"; shift 2;;
           --pluginsetup-conf)               shift 2;;
           --setupplugin-conf)               shift 2;;
           --vdr)                            shift 2;;
           --switchterminal)                 shift 2;;
           --xserver)                        shift 2;;
           --runvdr-pid)                     shift 2;;
           --dvb-load)                       shift 2;;
           --dvb-unload)                     shift 2;;
           --dvb-unload-on-exit)             shift  ;;
           --x-startup)                      shift 2;;
           --x-shutdown)                     shift 2;;
           --language)                       shift 2;;
           --charset-override)               shift 2;;
           --wrapper)                        shift 2;;
           --term-timeout)                   shift 2;;
           --kill-timeout)                   shift 2;;
           --terminate)                      shift 2;;
           --wait)                           shift 2;;
           --restart)                        shift 2;;
           --dvb-restart)                    shift 2;;
           --maxrestarts)                    shift 2;;
           --restarttime)                    shift 2;;
        -h|--help)                           shift  ;;
        -V|--version)                        shift  ;;

        -a|--audio)                          shift 2;;
           --cachedir)                       shift 2;;
        -c|--config)                         shift 2;;
        -d|--daemon)                         shift  ;;
        -D|--device)                         shift 2;;
           --dirnames)                       shift 2;;
        -E|--epgfile)                        shift 2;;
        -g|--grab)                           shift  ;;
        -i|--instance)                       shift 2;;
        -l|--log)                            shift 2;;
        -L|--lib)                            shift 2;;
           --lirc)                           shift 2;;
           --localedir)                      shift 2;;
        -m|--mute)                           shift  ;;
           --no-kbd)                         shift  ;;
        -p|--port)                           shift 2;;
        -P|--plugin)                         shift 2;;
           --rcu)                            shift 2;;
        -r|--record)                         shift 2;;
           --resdir)                         shift 2;;
        -s|--shutdown)                       shift 2;;
        -t|--terminal)                       shift 2;;
        -u|--user)                           shift 2;;
           --userdump)                       shift  ;;
        -v|--video)                          shift 2;;
           --vfat)                           shift  ;;
        -w|--watchdog)                       shift 2;;

        --)
            shift
            break
            ;;
        *)
            echo "Internal error!" >&2
            exit 1
            ;;
    esac ; done
}

function Clean() {
    # Clean all config variables
    ADDPARAM=
    ADDPARAMS=()
    PLUGINSETUPCONF=
    SETUPPLUGINCONF=
    VDRPRG=vdr
    SWITCHTERMINAL=
    XSERVER=
    RUNVDRPID=
    DVBLOAD=
    DVBUNLOAD=
    DVBUNLOADONEXIT=
    XSTARTUP=
    XSHUTDOWN=
    LANGUAGE=
    export VDR_CHARSET_OVERRIDE=
    WRAPPER=
    TERMTIMEOUT=
    KILLTIMEOUT=
    TERMINATE=
    RESTART=
    DVBRESTART=
    MAXRESTARTS=5
    RESTARTTIME=10
    WAIT=0
    HELP=
    VERSION=

    AUDIO=
    CACHEDIR=
    CONFIGDIR=
    DAEMON=
    DVBDEVICE=()
    DIRNAMES=
    EPGFILE=
    GRAB=
    INSTANCE=
    LIBDIR=
    LIRC=
    LOGLEVEL=
    LOCALEDIR=
    MUTE=
    NOKBD=
    PLUGINS=()
    SVDRPPORT=
    RECORDCMD=
    RESDIR=
    RCU=
    SHUTDOWN=
    TERMINAL=
    USER=
    USERDUMP=
    VFAT=
    VIDEODIR=
    WATCHDOG=
}


# Helper functions
function AddPluginString() {
    # add $1 as plugin

    if [ -n "$1" -a -z "${1##-*}" ] ; then
        local pattern="${1#-}*"

        local -a plugins1
        plugins1=("${PLUGINS[@]}")
        PLUGINS=()

        for i in "${plugins1[@]}" ; do
            [ -n "${i##$pattern}" ] && PLUGINS[${#PLUGINS[*]}]="$i";
        done
    else
        [ -n "$1" ] && PLUGINS[${#PLUGINS[*]}]="$1";
    fi
    return 0
}
function AddPlugin() {
    # add $* as plugin, do shell quoting

    local plugin=""
    while [ $# -gt 0 ] ; do
        # regexp magic
        # quote '\' to '\\'
        local par="$1"
        par="${par//'\'/\\\\}"
        # work around bash bug: double quoted '\'
        par="${par//'\\'/\\\\}"
        # quote '"' to '\"'
        par="${par//\"/\\\"}"
        # check if this splits into words
        local -a arr=($par)
        # if yes, wrap in quotes
        [ ${#arr[*]} -ne 1 ] && par="\"$par\""
        # add to plugin string
        if [ -n "$plugin" ] ; then plugin="$plugin $par" ; else plugin="$par" ; fi
        # next, please
        shift
    done
    AddPluginString "$plugin"
}
function AddDevice() {
    if [ -n "$1" -a -z "${1##-*}" ] ; then
        local pattern="${1#-}*"

        local -a devices1
        devices1=("${DVBDEVICE[@]}")
        DVBDEVICE=()

        for i in "${devices1[@]}" ; do
            [ -n "${i##$pattern}" ] && DVBDEVICE[${#DVBDEVICE[*]}]="$i";
        done
    else
        [ -n "$1" ] && DVBDEVICE[${#DVBDEVICE[*]}]="$1";
    fi
}

function AddParams() {
    # Add to unparsed parameter list
    for i ; do
    	ADDPARAMS[${#ADDPARAMS[*]}]="$i"
    done
}

function INCLUDE() {
    # include different conf file(s)

    for file ; do
        if [ -r "$file" ] ; then
            . "$file" || exit 1
        else
            echo "runvdr: $file not found." >&2
        fi
    done
}

function LoadConfFile() {

    # Load configuration file

    VDRUSER=""
    # Old option, supported for compatibility only

    if [ -z "$RUNVDRCONF" -a -r ~/.$RUNVDR.conf ] ; then
        RUNVDRCONF=~/.$RUNVDR.conf
    fi
    if [ -z "$RUNVDRCONF" -a -r /etc/$RUNVDR.conf ] ; then
        RUNVDRCONF=/etc/$RUNVDR.conf
    fi
    if [ -z "$RUNVDRCONF" -a -r ~/.runvdr.conf ] ; then
        RUNVDRCONF=~/.runvdr.conf
    fi
    if [ -z "$RUNVDRCONF" -a -r /etc/runvdr.conf ] ; then
        RUNVDRCONF=/etc/runvdr.conf
    fi
    if [ -n "$RUNVDRCONF" ] ; then
        if [ -r "$RUNVDRCONF" ] ; then
            . "$RUNVDRCONF" || { echo "runvdr: $RUNVDRCONF returned with $?." >&2 ; exit 1 ; }
        else
            echo "runvdr: $RUNVDRCONF not found." >&2
        fi
    fi

    if [ -n "$VDRUSER" ] ; then
        echo "runvdr: VDRUSER is deprecated. Use USER= instead."
        [ -n "$USER" ] && USER="$VDRUSER"
    fi

    # Transform some defaults, so empty parameters can have a
    # non-default meaning
    [ -z "$LIRC" ] && LIRC=0
    [ -z "$RCU"  ] && RCU=0
    [ -z "$TERMINATE" ] && TERMINATE=0
    [ -z "$RESTART" ] && RESTART=0
    [ -z "$DVBRESTART" ] && DVBRESTART=0
    [ -z "$MAXRESTARTS" ] && MAXRESTARTS=5
    [ -z "$RESTARTTIME" ] && RESTARTTIME=10

    # Compatibility: Map old ADDPARAM to new AddParams
    [ -n "$ADDPARAM" ] && eval "AddParams $ADDPARAM"

    return 0
}


function ParseCommandLine_Step2() {
    # Parse command line, step 2
    # Process all options in $OPTIONS, override
    # all options that are set by now

    eval set -- "$OPTIONS"

    while true ; do case "$1" in
        -C|--runvdr-conf)                    shift 2;;
           --xserver-proxy)                  shift 2;;
           --pluginsetup-conf) PLUGINSETUPCONF="$2"; shift 2;;
           --setupplugin-conf) SETUPPLUGINCONF="$2"; shift 2;;
           --vdr)          VDRPRG="$2";      shift 2;;
           --switchterminal) SWITCHTERMINAL="$2"; shift 2;;
           --xserver)      XSERVER="$2";     shift 2;;
           --runvdr-pid)   RUNVDRPID="$2";   shift 2;;
           --dvb-load)     DVBLOAD="$2";     shift 2;;
           --dvb-unload)   DVBUNLOAD="$2";   shift 2;;
           --dvb-unload-on-exit) DVBUNLOADONEXIT=1; shift  ;;
           --x-startup)    XSTARTUP="$2";    shift 2;;
           --x-shutdown)   XSHUTDOWN="$2";   shift 2;;
           --language)     LANGUAGE="$2";    shift 2;;
           --charset-override) VDR_CHARSET_OVERRIDE="$2"; shift 2;;
           --wrapper)      WRAPPER="$2";     shift 2;;
           --term-timeout) TERMTIMEOUT="$2"; shift 2;;
           --kill-timeout) KILLTIMEOUT="$2"; shift 2;;
           --terminate)    TERMINATE="$2";   shift 2;;
           --wait)         WAIT="$2";        shift 2;;
           --restart)      RESTART="$2";     shift 2;;
           --dvb-restart)  DVBRESTART="$2";  shift 2;;
           --maxrestarts)  MAXRESTARTS="$2"; shift 2;;
           --restarttime)  RESTARTTIME="$2"; shift 2;;
        -h|--help)         HELP=1;           shift  ;;
        -V|--version)      VERSION=1;        shift  ;;


        -a|--audio)        AUDIO="$2";     shift 2;;
           --cachedir)     CACHEDIR="$2";  shift 2;;
        -c|--config)       CONFIGDIR="$2"; shift 2;;
        -d|--daemon)       DAEMON=1;       shift  ;;
        -D|--device)       AddDevice "$2"; shift 2;;
           --dirnames)     DIRNAMES="$2";  shift 2;;
        -E|--epgfile)      EPGFILE="$2";   shift 2;;
        -g|--grab)         GRAB="1";       shift  ;;
        -i|--instance)     INSTANCE="$2";  shift 2;;
        -l|--log)          LOGLEVEL="$2";  shift 2;;
        -L|--lib)          LIBDIR="$2";    shift 2;;
           --lirc)         LIRC="$2";      shift 2;;
           --localedir)    LOCALEDIR="$2"; shift 2;;
        -m|--mute)         MUTE=1;         shift  ;;
           --no-kbd)       NOKBD=1;        shift  ;;
        -p|--port)         SVDRPPORT="$2"; shift 2;;
        -P|--plugin)       AddPluginString "$2"; shift 2;;
           --rcu)          RCU="$2";       shift 2;;
        -r|--record)       RECORDCMD="$2"; shift 2;;
           --resdir)       RESDIR="$2";    shift 2;;
        -s|--shutdown)     SHUTDOWN="$2";  shift 2;;
        -t|--terminal)     TERMINAL="$2";  shift 2;;
        -u|--user)         USER="$2";      shift 2;;
           --userdump)     USERDUMP="$2";  shift  ;;
        -v|--video)        VIDEODIR="$2";  shift 2;;
           --vfat)         VFAT=1;         shift  ;;
        -w|--watchdog)     WATCHDOG="$2";  shift 2;;


        --)
            shift
            break
            ;;
        *)
            echo "Internal error!" >&2
            exit 1
            ;;
    esac ; done

    # Add all remaining options directly to additional params

	AddParams "$@"

    return 0
}



function OnlineHelp() {
    cat <<END-OF-HELP
Usage: $0 [OPTIONS]

runvdr Options:
-C #, --runvdr-conf=# location of runvdr config file
--pluginsetup-conf=#  location of plugin-setup-runvdr.conf
--setupplugin-conf=#  setup-plugin sysconfig
--vdr=#               location and name of the vdr binary
--switchterminal=#    console terminal number to switch to
--xserver=#           fire up own X server for VDR
--runvdr-pid=#        location of runvdr.pid file
--dvb-load=#          command to load DVB drivers
--dvb-unload=#        command to unload DVB drivers
--dvb-unload-on-exit  do unload DVB drivers on exit
--x-startup=#         command executed after X startup
--x-shutdown=#        command executed before X shutdown
--wrapper=#           wrapper command for calling vdr
--language=#          Locale to set for VDR
--charset-override=#  Override VDR charset
--terminate[=#]       Terminate runvdr by pid
--wait[=#]            Wait # seconds for --terminate to finish
--restart[=#]         Send restart signal by pid
--dvb-restart[=#]     Send dvb-restart signal by pid
--term-timeout=#      Timeout for VDR to react on SIGTERM
--kill-timeout=#      Timeout for VDR to react on SIGKILL
--maxrestarts=#       Max number of rapid restarts before give-up
--restarttime=#       Max time for restart to be rapid

-V, --version         print version information and exit
-h, --help            print this help and exit

Parsed VDR options:
-a # --audio=#     send Dolby Digital audio to stdin of command CMD
     --cachedir=#  save cache files in DIR
-c # --config=#    read config files from DIR
-d   --daemon      run in daemon mode
-D # --device=#    use only the given DVB device (NUM = 0, 1, 2...)
                   Use '-' to override devices from config file
                   Use '-x' to ignore device x from config file
     --dirnames=PATH[,NAME[,ENC]]
                   set the maximum directory path length to PATH; if NAME is
                   also given, it defines the maximum directory name length;
                   the optional ENC can be 0 or 1, and controls whether
                   special characters in directory names are encoded as
                   hex values (default: 0); if PATH or NAME are left empty
                   (as in ",,1" to only set ENC), the defaults apply
-E # --epgfile=#   write the EPG data into the given FILE. - to disable.
-g # --grab=#      write images from the SVDRP command GRAB into the given DIR
-i # --instance=#  use ID as the id of this VDR instance
-L # --lib=#       search for plugins in DIR
     --lirc[=#]    use a LIRC remote control device, attached to PATH
     --localedir=# search for locale files in DIR
-l # --log=#       set log level
-m   --mute        mute audio of the primary DVB device at startup
     --no-kbd      don't use the keyboard as an input device
-P # --plugin=#    load a plugin defined by the given options
                   Use '-' to ignore all plugins from config file
                   Use '-xx' to ignore plugin xx from config file
-p # --port=#      use PORT for SVDRP
     --rcu[=#]     use a remote control device, attached to PATH
-r # --record=#    call CMD before and after a recording
     --resdir=#    read resource files from DIR
-s # --shutdown=#  call CMD to shutdown the computer
-t # --terminal=#  controlling tty
-u # --user=#      run as user USER; only applicable if started as root
     --userdump    allow coredumps if -u is given (debugging)
     --vfat        for backwards compatibility (same as --dirnames=250,40,1)
-v # --video=#     use DIR as video directory
-w # --watchdog=#  activate the watchdog timer with a timeout of SEC

All runvdr parameters after '--' will be passed to VDR without modification
END-OF-HELP
}


function AddCommandLine() {
    # Add all parameters to command line array
    for params ; do
    	VDRCOMMAND[${#VDRCOMMAND[*]}]="$params"
    done
}

function BuildCommand() {
    # Based on all options, build command line in ${VDRCOMMAND[]}

    VDRCOMMAND=()

    # complete command with path
    VDRPRG=`which "$VDRPRG"`
    if [ -z "$VDRPRG" ] ; then
        echo "VDR command binary not found."
        exit 1
    fi

    # Build up command line:

    [ -n "$WRAPPER"   ] && AddCommandLine $WRAPPER
    # No quotes around $WRAPPER!

    AddCommandLine "$VDRPRG"

    [ "${#ADDPARAMS[*]}" -gt 0 ] && AddCommandLine "${ADDPARAMS[@]}"

    [ -n "$AUDIO"     ] && AddCommandLine -a "$AUDIO"
    [ -n "$CACHEDIR"  ] && AddCommandLine --cachedir="$CACHEDIR"
    [ -n "$CONFIGDIR" ] && AddCommandLine -c "$CONFIGDIR"
    [ -n "$DAEMON"    ] && AddCommandLine -d

    for i in "${DVBDEVICE[@]}" ; do
        [ -n "$i" ] && AddCommandLine -D "$i"
    done

    [ -n "$DIRNAMES"  ] && AddCommandLine --dirnames="$DIRNAMES"
    [ -n "$EPGFILE"   ] && AddCommandLine -E "$EPGFILE"
    [ -n "$GRAB"      ] && AddCommandLine -g "$GRAB"
    [ -n "$INSTANCE"  ] && AddCommandLine -i "$INSTANCE"
    [ -n "$LOGLEVEL"  ] && AddCommandLine -l "$LOGLEVEL"
    [ -n "$LIBDIR"    ] && AddCommandLine -L "$LIBDIR"
    case "$LIRC" in
        1|"") AddCommandLine --lirc;;
        0) ;;
        *) AddCommandLine --lirc="$LIRC";;
    esac
    [ -n "$LOCALEDIR" ] && AddCommandLine --localedir "$LOCALEDIR"
    [ -n "$MUTE"      ] && AddCommandLine -m
    [ -n "$NOKBD"     ] && AddCommandLine --no-kbd
    [ -n "$SVDRPPORT" ] && AddCommandLine -p "$SVDRPPORT"

    for p in "${PLUGINS[@]}" ; do
        if [ -n "$p" ] ; then
            AddCommandLine -P "$p"
        fi
    done

    if [ -n "$PLUGINSETUPCONF" ] ; then
        eval "AddCommandLine `< $PLUGINSETUPCONF`"
    fi

    if [ -n "$SETUPPLUGINCONF" ] ; then
        while read -r line ; do
            [ "${line:0:11}" == "PLUGINLIST=" ] && eval "eval \"AddCommandLine ${line:11}\""
        done < "$SETUPPLUGINCONF"
    fi

    [ -n "$RECORDCMD" ] && AddCommandLine -r "$RECORDCMD"
    case "$RCU" in
        1|"") AddCommandLine --rcu;;
        0) ;;
        *) AddCommandLine --rcu="$RCU";;
    esac

    [ -n "$RESDIR"    ] && AddCommandLine --resdir="$RESDIR"
    [ -n "$SHUTDOWN"  ] && AddCommandLine -s "$SHUTDOWN"
    [ -n "$TERMINAL"  ] && AddCommandLine -t "$TERMINAL"
    [ -n "$USER"      ] && AddCommandLine -u "$USER"
    [ -n "$USERDUMP"  ] && AddCommandLine --userdump
    [ -n "$VFAT"      ] && AddCommandLine --vfat
    [ -n "$VIDEODIR"  ] && AddCommandLine -v "$VIDEODIR"
    [ -n "$WATCHDOG"  ] && AddCommandLine -w "$WATCHDOG"


    [ -z "$TERMTIMEOUT" ] && TERMTIMEOUT=20
    [ -z "$KILLTIMEOUT" ] && KILLTIMEOUT=5

    return 0
}

function GetChilds() {
    # Get PIDs of all forked childs of PID=$1, binary executable=$2
    # Returns list of PIDs in childlist

    child="$1"
    childlist=($child)
    IFSBACKUP="$IFS"
    for ((i=0;i<10;i++)) do
        len=${#childlist[*]}
        IFS=","
        child=`{ echo "$child" ; $PGREP -f "^$2 " -P "${childlist[*]}" ; } | sort -u`
        IFS="$IFSBACKUP"
        childlist=($child)

        [ "$len" -eq "${#childlist[*]}" ] && break
    done
}

function WaitKill() {
    # Terminates/Kills process $1, binary $2, timeout1 $3, timeout2 $4

    GetChilds "$1" "$2"

    echo -n "Sending ${#childlist[*]} processes the TERM signal."
    kill -TERM ${childlist[*]} 2>/dev/null

    for ((i=0;i<$3;i++)) ; do
        $PS ${childlist[*]} >/dev/null || { echo terminated. ; return ; }

        echo -n .
        $SLEEP 1
    done
    echo

    echo -n "Sending ${#childlist[*]} processes the KILL signal."
    kill -KILL ${childlist[*]} 2>/dev/null

    for ((i=0;i<$4;i++)) ; do
        $PS ${childlist[*]} >/dev/null || { echo terminated. ; return ; }
        echo -n .
        $SLEEP 1
    done
    echo failed.
}

# Helper functions for callbacks

function Do_DVBLOAD() {
    if [ -n "$DVBLOAD" ] ; then
        eval "$DVBLOAD"
    elif [ "`type -t DVBLOAD`" = "function" ] ; then
        DVBLOAD
    fi
}

function Do_DVBUNLOAD() {
    if [ -n "$DVBUNLOAD" ] ; then
        eval "$DVBUNLOAD"
    elif [ "`type -t DVBUNLOAD`" = "function" ] ; then
        DVBUNLOAD
    fi
}

function Do_XSTARTUP() {
    if [ -n "$XSTARTUP" ] ; then
        eval "$XSTARTUP"
    elif [ "`type -t XSTARTUP`" = "function" ] ; then
        XSTARTUP
    fi
}

function Do_XSHUTDOWN() {
    # X shutdown command
    if [ -n "$XSHUTDOWN" ] ; then
        eval "$XSHUTDOWN"
    elif [ "`type -t XSHUTDOWN`" = "function" ] ; then
        XSHUTDOWN
    fi
}



#### ---------------
####   Main script
#### ---------------


# Parse command line, step 1
ParseCommandLine_Step1 "$@" || exit 1

# Act as a proxy for calling VDR, from within X session
if [ -n "$XSERVERPROXY" ] ; then
    # X startup command
    Do_XSTARTUP
    # Unpack proxy command line
    eval "VDRCOMMAND=($VDRCOMMANDPROXY)"
    "${VDRCOMMAND[@]}" &
    PID=$!
    echo "PID $PID" > "$XSERVERPROXY"
    wait $PID
    echo "RET $?" >> "$XSERVERPROXY"
    # X shutdown command
    Do_XSHUTDOWN
    exit 0
fi

# Clean variables
Clean

# Load and process all configuration
LoadConfFile || exit 1

# Process command line
ParseCommandLine_Step2 || exit 1


if [ -n "$HELP" ] ; then
    OnlineHelp
    exit 0
fi

if [ -n "$VERSION" ] ; then
    echo "runvdr extreme version 0.4.2"
    exit 0
fi

# Get old runvdr pid and move it to options
if [ -n "$RUNVDRPID" ] ; then
    OLDRUNVDRPID=""
    [ -r "$RUNVDRPID" ] && OLDRUNVDRPID=`<$RUNVDRPID`

    [ -z "$TERMINATE"  ] && TERMINATE="$OLDRUNVDRPID"
    [ -z "$RESTART"    ] && RESTART="$OLDRUNVDRPID"
    [ -z "$DVBRESTART" ] && DVBRESTART="$OLDRUNVDRPID"
fi

if [ "$TERMINATE" != "0" ] ; then
    if [ -n "$TERMINATE" ] ; then
        echo -n "Terminating runvdr (PID=$TERMINATE)"
        kill -TERM $TERMINATE
        while [ -z "$WAIT" ] || [ "$WAIT" -gt 0 ] ; do
            $PS $TERMINATE >/dev/null || { echo done ; break ; }
            echo -n "."
            $SLEEP 1
            [ -n "$WAIT" ] && let WAIT=WAIT-1
        done

        echo ""
    else
        echo "No runvdr process to terminate."
    fi
    exit 0
fi

if [ "$RESTART" != "0" ] ; then
    if [ -n "$RESTART" ] ; then
       echo -n "Restarting runvdr (PID=$RESTART)..."
       kill -USR1 $RESTART
       echo ""
    else
        echo "No runvdr process to restart."
    fi
    exit 0
fi

if [ "$DVBRESTART" != "0" ] ; then
    if [ -n "$DVBRESTART" ] ; then
        echo -n "DVB-restarting runvdr (PID=$DVBRESTART)..."
        kill -USR2 $DVBRESTART
        echo ""
    else
        echo "No runvdr process to dvb-restart."
    fi
    exit 0
fi


# Build up VDR command
BuildCommand || exit 1


# Switch front console

[ -n "$SWITCHTERMINAL" ] && $CHVT $SWITCHTERMINAL

if [ -n "$LANGUAGE" ] ; then
    LC_ALL="$LANGUAGE"
    export LC_ALL
fi

# Remember PID of this process

[ -n "$RUNVDRPID" ] && echo $$ > $RUNVDRPID


# Prepare terminal redirection
if [ -n "$TERMINAL" ] ; then
    exec 1>"$TERMINAL"
    exec 2>"$TERMINAL"
fi


# Load driver if it hasn't been loaded already:
Do_DVBLOAD

# Count how often VDR terminated very quickly
SHORTRUNTIMES=0

# Initialize for now
PROXYFILE=

while (true) do
    echo -n "Starting VDR at " ; $DATE

    # Trap some signals sent to this script
    trap "SIG=HUP" SIGHUP
    trap "SIG=INT" SIGINT
    trap "SIG=QUIT" SIGQUIT
    trap "SIG=TERM" SIGTERM
    trap "SIG=USR1" SIGUSR1
    trap "SIG=USR2" SIGUSR2

    # clean up signal variable
    SIG=

    # Remember start time
    STARTTIME=`$DATE +%s`

    echo "${VDRCOMMAND[@]}"

    if [ -z "$XSERVER" ] ; then
        # Run VDR
        "${VDRCOMMAND[@]}" &

        # Remember PID of VDR process
        PID=$!

        # no X server PID
        XSERVERPID=

        # Wait for VDR to end or signal to arrive
        wait $PID

        # Remember return value of VDR
        RET=$?
    else
        # Run X server that runs VDR
        PROXYFILE="/tmp/runvdr-$$"
        [ -f "$PROXYFILE" ] && rm "$PROXYFILE"

        # Pack command array into single env string:
        export VDRCOMMANDPROXY=`printf '%q ' "${VDRCOMMAND[@]}"`
        export XSTARTUP
        export XSHUTDOWN
        [ "`type -t XSTARTUP`" = "function" ] && export -f XSTARTUP
        [ "`type -t XSHUTDOWN`" = "function" ] && export -f XSHUTDOWN

        # Fire up X server that calls back runvdr, and run into XSERVERPROXY there
        eval "xinit \""$0"\" --xserver-proxy=\""$PROXYFILE"\" -- $XSERVER &"

        # Remember X server PID
        XSERVERPID=$!

        # ... also temporary as VDR PID
        PID=$XSERVERPID

        # Wait for VDR to end or signal to arrive
        wait $XSERVERPID

        # No known return of VDR yet
        RET=0
    fi

    # If proxy, read proxy return values
    if [ -n "$PROXYFILE" ] ; then
        while read var arg ; do case "$var" in
            PID) PID="$arg";;
            RET) RET="$arg";;
        esac ; done < "$PROXYFILE"
        rm "$PROXYFILE"
    fi

    # Remember stop time
    STOPTIME=`$DATE +%s`
    # Count if time is less than RESTARTTIME seconds,
    # forget otherwise
    if [ "$RESTARTTIME" -gt 0 -a $((STOPTIME-STARTTIME)) -le "$RESTARTTIME" ] ; then
        SHORTRUNTIMES=$((SHORTRUNTIMES+1))
        echo "VDR died within $RESTARTTIME seconds, this happened $SHORTRUNTIMES time(s)."
    else
        SHORTRUNTIMES=0
    fi

    case "$SIG" in
      HUP | INT | QUIT | TERM)
        echo -n "Terminating by request at " ; $DATE

        # Kill remaining VDR traces
        WaitKill $PID $VDRPRG $TERMTIMEOUT $KILLTIMEOUT

        # Wait for X server to be down too
        [ "$XSERVERPID" ] && wait "$XSERVERPID"

        # Unload DVB drivers requested?
        [ -n "$DVBUNLOADONEXIT" ] && Do_DVBUNLOAD

        # and exit
        break
        ;;
      USR1)
        echo -n "Restarting VDR by request at " ; $DATE

        # Kill remaining VDR traces
        WaitKill $PID $VDRPRG $TERMTIMEOUT $KILLTIMEOUT

        # Wait for X server to be down too
        [ "$XSERVERPID" ] && wait "$XSERVERPID"

        # and loop
        ;;
      USR2)
        echo -n "Restarting VDR and DVB by request at " ; $DATE

        # Kill remaining VDR traces
        WaitKill $PID $VDRPRG $TERMTIMEOUT $KILLTIMEOUT

        # Wait for X server to be down too
        [ "$XSERVERPID" ] && wait "$XSERVERPID"

        # reload DVB stuff
        Do_DVBUNLOAD
        Do_DVBLOAD
        ;;
      *)  # Non-signal termination
        if [ $RET -eq 0 -o $RET -eq 2 ] ; then
            echo -n "Terminating by error level $RET at " ; $DATE

            # Kill remaining VDR traces
            WaitKill $PID $VDRPRG $TERMTIMEOUT $KILLTIMEOUT

            # Wait for X server to be down too
            [ "$XSERVERPID" ] && wait "$XSERVERPID"

            # Unload DVB drivers requested?
            [ -n "$DVBUNLOADONEXIT" ] && Do_DVBUNLOAD

            # and exit
            break
        fi
        if [ $SHORTRUNTIMES -gt "$MAXRESTARTS" ] ; then
            echo -n "Terminating because VDR died $SHORTRUNTIMES times in a row quickly at " ; $DATE

            # Kill remaining VDR traces
            WaitKill $PID $VDRPRG $TERMTIMEOUT $KILLTIMEOUT

            # Wait for X server to be down too
            [ "$XSERVERPID" ] && wait "$XSERVERPID"

            # Unload DVB drivers requested?
            [ -n "$DVBUNLOADONEXIT" ] && Do_DVBUNLOAD

            # and exit
            break;
        fi
        echo -n "Restarting VDR and DVB by error level $RET at " ; $DATE

        # Kill remaining VDR traces
        WaitKill $PID $VDRPRG $TERMTIMEOUT $KILLTIMEOUT

        # Wait for X server to be down too
        [ "$XSERVERPID" ] && wait "$XSERVERPID"

        # reload DVB
        Do_DVBUNLOAD
        Do_DVBLOAD

        # and loop
        ;;
    esac

    # reload configuration
    Clean
    LoadConfFile || exit 1
    ParseCommandLine_Step2 || exit 1
    BuildCommand || exit 1

    # Catch remaining in-between signals
    case "$SIG" in
      HUP | INT | QUIT | TERM)
        break
        ;;
    esac
done

# Clean up PID file
[ -n "$RUNVDRPID" ] && rm $RUNVDRPID 2>/dev/null

# Clean up proxy file, if used
[ -n "$PROXYFILE" ] && rm $PROXYFILE 2>/dev/null