#!/bin/bash

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

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

ACTION="$1"
shift

trap '' SIGHUP

killwait() {
    kill $(cat "$2")
    if ! waitlock $1 "$2"; then
        kill -9 $(cat "$2")
        return 1
    fi

    return 0
}

case "$ACTION" in
    start | check)
        ulimit -n $(ulimit -Hn) 2>/dev/null

        if trylock $PIDDIR/seedlink.pid; then
            echo "starting seedlink"
            seedlink -v \
              -f $CFGDIR/seedlink.ini \
              >> $LOGDIR/seedlink.log 2>&1 &
        else
            echo "seedlink is running"
        fi

        if [ "$(echo $CFGDIR/slarchive_*)" != "$CFGDIR/slarchive_*" ]; then
            for f in $CFGDIR/slarchive_*; do
                host="$(echo ${f##*/slarchive_} | cut -d '_' -f 1)"
                port="$(echo ${f##*/slarchive_} | cut -d '_' -f 2)"
                if trylock "$PIDDIR/slarchive_${host}_${port}.pid"; then
                    echo "starting client slarchive $host:$port"
                    run_with_lock "$PIDDIR/slarchive_${host}_${port}.pid" slarchive -x "$PIDDIR/slarchive_${host}_${port}.seq:100" -SDS "$ARCDIR" -nt 900 -Fi:1 -Fc:900 -l "$f" $host:$port >>"$LOGDIR/slarchive_${host}_${port}.log" 2>&1 &
                else
                    echo "client slarchive $host:$port is running"
                fi
            done
        fi
        ;;
    stop)
        if [ "$(echo $CFGDIR/slarchive_*)" != "$CFGDIR/slarchive_*" ]; then
            for f in $CFGDIR/slarchive_*; do
                host="$(echo ${f##*/slarchive_} | cut -d '_' -f 1)"
                port="$(echo ${f##*/slarchive_} | cut -d '_' -f 2)"
                if trylock "$PIDDIR/slarchive_${host}_${port}.pid"; then
                    echo "client slarchive $host:$port is not running"
                else
                    echo "shutting down client slarchive $host:$port"
                    killwait 10 $PIDDIR/slarchive_${host}_${port}.pid >/dev/null 2>&1
                fi
            done
        fi

        if [ $# -eq 0 ]; then
            if trylock $PIDDIR/seedlink.pid; then
                echo "seedlink is not running"
            else
                echo "shutting down seedlink"
                killwait 30 $PIDDIR/seedlink.pid >/dev/null 2>&1
            fi
            rm -f $PIDDIR/seedlink.pid
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|check}"
        exit 1
esac

