#!/bin/bash

# Generated at Wed Nov  7 21:51:03 CET 2012 - Do not edit!
# template: /DB/HOME/nerces/SISMO/SEISCOMP/seiscomp-2.6/qplot/templates/qplot_ctrl.tpl

CFGDIR=/DB/HOME/nerces/SISMO/SEISCOMP/seiscomp-2.6/qplot/config
LOGDIR=/DB/HOME/nerces/SISMO/SEISCOMP/seiscomp-2.6/qplot/log
PIDDIR=/DB/HOME/nerces/SISMO/SEISCOMP/seiscomp-2.6/qplot/status

ACTION="$1"
shift

if [ $# -gt 0 ]; then
    STATIONS="$*"
else
    STATIONS=$(for f in $CFGDIR/rc_*; do echo "${f##*_}"; done)
fi

trap '' SIGHUP

case "$ACTION" in
    start | check)
        for s in $STATIONS; do
            if [ -f $CFGDIR/clients_$s ]; then
                cat $CFGDIR/clients_$s | while read line; do
                    name="${line%% *}"
                    cmd="${line#* }"
                    
                    test -z "$name" -o -z "$cmd" && continue
                    
                    if trylock $PIDDIR/$s.$name.pid; then
                        echo "starting client \"$name\" of station $s"
                        sh -c "$cmd" >> $LOGDIR/$s.$name.log 2>&1 &
                    else
                        echo "client \"$name\" of station $s is running"
                    fi
                done
            fi
        done

        ;;
    stop)
        for s in $STATIONS; do
            if [ -f $CFGDIR/clients_$s ]; then
                cat $CFGDIR/clients_$s | while read line; do
                    name="${line%% *}"
                    cmd="${line#* }"
                    
                    test -z "$name" -o -z "$cmd" && continue
                    
                    if trylock $PIDDIR/$s.$name.pid; then
                        echo "client \"$name\" of station $s is not running"
                    else
                        echo "shutting down client \"$name\" of station $s"
                        kill $(cat $PIDDIR/$s.$name.pid) >/dev/null 2>&1
                    fi
                    
                    rm -f $PIDDIR/$s.$cexec.pid
                done
            fi
        done
        ;;
    *)
        echo "Usage: $0 {start|stop|check}"
        exit 1
esac

