#!/usr/bin/env bash

start() {
    KEYSTORE=/var/lib/bee-clef/keystore
    CONFIGDIR=/var/lib/bee-clef
    CHAINID=5
    SECRET=$(cat /var/lib/bee-clef/password)
    # clef with every start sets permissions back to 600
    (while [ ! -f /var/lib/bee-clef/clef.ipc ]; do sleep 1; done && chmod 660 /var/lib/bee-clef/clef.ipc) &
    rm /var/lib/bee-clef/stdin /var/lib/bee-clef/stdout || true
    mkfifo /var/lib/bee-clef/stdin /var/lib/bee-clef/stdout
    (
    exec 3>/var/lib/bee-clef/stdin
    while read < /var/lib/bee-clef/stdout
    do
        if [[ "$REPLY" =~ "enter the password" ]]; then
            echo '{ "jsonrpc": "2.0", "id":1, "result": { "text":"'"$SECRET"'" } }' > /var/lib/bee-clef/stdin
            break
        fi
    done
    ) &
    clef --stdio-ui --keystore $KEYSTORE --configdir $CONFIGDIR --chainid $CHAINID --rules /etc/bee-clef/rules.js --nousb --4bytedb-custom /etc/bee-clef/4byte.json --pcscdpath "" --auditlog "" --loglevel 3 --ipcpath /var/lib/bee-clef < /var/lib/bee-clef/stdin | tee /var/lib/bee-clef/stdout
}

stop() {
    echo "STOP! Systemd will stop the service!"
}

case $1 in
    start|stop) "$1"
esac
