#!/bin/bash

if [ -z "$SEISCOMP_ROOT" ]; then
    echo "SEISCOMP_ROOT is not defined"
    exit 1
fi

pkgname="seisgram"
PKGROOT="$SEISCOMP_ROOT/$pkgname"

export PATH="$PKGROOT/bin:$PATH"

if ! cd "$PKGROOT"; then
    echo "Cannot change directory to $PKGROOT"
    exit 1
fi

if [ ! -r "$SEISCOMP_ROOT/lib/env.sh" ]; then
    echo "Cannot read $SEISCOMP_ROOT/lib/env.sh"
    exit 1
fi

source "$SEISCOMP_ROOT/lib/env.sh"

if [ ! -r "$SEISCOMP_ROOT/lib/keyutils.sh" ]; then
    echo "Cannot read $SEISCOMP_ROOT/lib/keyutils.sh"
    exit 1
fi

source "$SEISCOMP_ROOT/lib/keyutils.sh"

global_cfg="templates/global.cfg"
if [ ! -r "$global_cfg" ]; then
    echo "Cannot read $PKGROOT/$global_cfg!"
    exit 1
fi

station_cfg="templates/station.cfg"
if [ ! -r "$station_cfg" ]; then
    echo "Cannot read $PKGROOT/$station_cfg!"
    exit 1
fi

VERSION="2.5"
KEY_VERSION="2.5"

_init_keys() {
    mkdir -p key

    SG_TRACELEN="1800"
    SG_MAXVISIBLE="20"
    SG_SELECTORS="BH?.D"
    SG_MIN_PEAKTOPEAK="auto"
    SG_MAX_PEAKTOPEAK="auto"
    SG_BACKFILL="no"
}

_edit_globals() {
    _init_keys

    if [ -f "key/global" ]; then
        source key/global
    fi

    Ask SG_TRACELEN "Trace length in seconds" "$SG_TRACELEN"
    Ask SG_MAXVISIBLE "Maximum number of visible traces" "$SG_MAXVISIBLE"
    AskYN SG_BACKFILL "Backfill traces" "$SG_BACKFILL"
    
    OutputKeys $global_cfg >key/global
}
 
_edit_keys() {
    _init_keys
    
    if [ -f "$keyfile" ]; then
        source "$keyfile"
    fi

    Ask SG_SELECTORS "Data stream selectors" "$SG_SELECTORS"
    Ask SG_MIN_PEAKTOPEAK "Minimum peak-to-peak display amplitude" "$SG_MIN_PEAKTOPEAK"
    Ask SG_MAX_PEAKTOPEAK "Maximum peak-to-peak display amplitude" "$SG_MAX_PEAKTOPEAK"

    OutputKeys $station_cfg >$keyfile
}

_get_keys() {
    pkg="$1"
    profile="$(echo -n "$PACKAGES" | sed -e "s/.*\<$pkg\>\(:\([^ ]*\)\)\?.*/\2/")"
    
    if [ -z "$profile" ]; then
        keyfile="$SEISCOMP_ROOT/$pkg/key/station_${NET}_${STATION}"
    else
        keyfile="$SEISCOMP_ROOT/$pkg/key/profile_$profile"
    fi

    if [ -f "$keyfile" ]; then
        source "$keyfile"
        return 0
    fi

    return 1
}

_write_conf() {
    LoadConfig "$global_cfg" "$station_cfg"

    _init_keys

    if [ ! -f "$SEISCOMP_ROOT/key/global" ]; then
        echo "Cannot find $SEISCOMP_ROOT/key/global"
        return
    fi

    source "$SEISCOMP_ROOT/key/global"
    
    if [ ! -f "key/global" ]; then
        echo "Cannot find $PKGROOT/key/global"
        return
    fi

    source "key/global"

    if [ ! -f "$SEISCOMP_ROOT/acquisition/key/global" ]; then
        echo "Cannot find $SEISCOMP_ROOT/acquisition/key/global"
    fi
    
    source "$SEISCOMP_ROOT/acquisition/key/global"
    
    mkdir -p config/store

    first=true
    for n in $SEISCOMP_ROOT/key/network_*; do
        if [ "$n" = "key/network_*" ]; then
            echo "No networks defined"
            break
        fi
        
        NET="${n##*_}"
        source $n

        echo "+ network $NET_DESC"
        
        for s in $SEISCOMP_ROOT/key/station_${NET}_*; do
            if [ "$s" = "key/station_${NET}_*" ]; then
                echo "No stations defined for network $NET"
                break
            fi

            STATION="${s##*_}"
            source $s

            echo "  + station $STAT_DESC"

            if echo $PACKAGES | grep -q "\<$pkgname\>"; then
                if ! _get_keys $pkgname; then
                    echo "    - cannot find $keyfile"
                    continue
                fi
            else
                echo "    - $pkgname not enabled for ${NET}_${STATION}"
                continue
            fi

            if echo $PACKAGES | grep -q "\<acquisition\>"; then
                if ! _get_keys acquisition; then
                    echo "    - cannot find $keyfile"
                    continue
                fi
            else
                echo "    - acquisition not enabled for ${NET}_${STATION} - disabling seisgram"
                continue
            fi
    
            if [ "$LOCALSOURCE" = seedlink ]; then
                SRCADDR=127.0.0.1
                SRCPORT="$SEEDLINK_PORT"
            elif [ "$LOCALSOURCE" = digiserv ]; then
                SRCADDR=127.0.0.1
                SRCPORT="$DIGISERV_PORT"
            fi
    
            file="config/store/sg_${SG_MIN_PEAKTOPEAK}:${SG_MAX_PEAKTOPEAK}:${SRCADDR}:${SRCPORT}"
            
            if [ -f "$file" ]; then
                echo -n "," >>"$file"
            fi
            
            echo -n "${NET}_${STATION}:${SG_SELECTORS}" >>"$file"
            first=false
        done
    done

    if $first; then
        :>config/seisgram.rc
        return
    fi

    echo -n "-seedlink \"" >config/seisgram.rc
    
    first=true
    for f in config/store/sg_*; do
        if ! $first; then
            echo -n ";" >>config/seisgram.rc
        fi
        
        parm="${f##*/sg_}"
        
        MIN_PEAKTOPEAK="$(echo $parm | cut -d ':' -f 1)"
        MAX_PEAKTOPEAK="$(echo $parm | cut -d ':' -f 2)"
        SRCADDR="$(echo $parm | cut -d ':' -f 3)"
        SRCPORT="$(echo $parm | cut -d ':' -f 4)"
        if [ "$MAX_PEAKTOPEAK" = auto ]; then
            if [ "$MIN_PEAKTOPEAK" = auto ]; then
                PEAKTOPEAK=""
            else
                PEAKTOPEAK="#${MIN_PEAKTOPEAK}"
            fi
        else
            if [ "$MIN_PEAKTOPEAK" = auto ]; then
                PEAKTOPEAK="#0#${MAX_PEAKTOPEAK}"
            else
                PEAKTOPEAK="#${MIN_PEAKTOPEAK}#${MAX_PEAKTOPEAK}"
            fi
        fi

        echo -n "${SRCADDR}:${SRCPORT}#$(cat $f)#${SG_TRACELEN}${PEAKTOPEAK}" >>config/seisgram.rc
        first=false
    done

    echo "\"" >>config/seisgram.rc
    echo "-seedlink.backfill $(echo $SG_BACKFILL | tr '[:lower:]' '[:upper:]')" >>config/seisgram.rc
    echo "-display.maxvisible $SG_MAXVISIBLE" >>config/seisgram.rc

    rm -rf config/store
}

action="$1"
shift

case "$action" in
    start|stop|check)
        exit 0
        ;;
    get_attributes)
        echo "globals,profile,station"
        exit 0
        ;;
    edit_globals)
        if [ $# -ne 0 ]; then
            break
        fi
        _edit_globals
        exit 0
        ;;
    edit_profile)
        if [ $# -ne 1 ]; then
            break
        fi
        keyfile="key/profile_$1"
        _edit_keys
        exit 0
        ;;
    edit_station)
        if [ $# -ne 2 ]; then
            break
        fi
        keyfile="key/station_$1_$2"
        _edit_keys
        exit 0
        ;;
    write_conf)
        _write_conf
        exit 0
        ;;
    print_crontab)
        exit 0
        ;;
esac

echo "Error: $pkgname config hook called with invalid arguments"
exit 1

