#!/usr/bin/env sh

set -e

# NOTE This file is called by the systemd service in its preStart
# hook, but it's not Nix specific in any way. Ideally, the same file
# should be called from the postinst scripts of the other packages,
# but... the world is not ideal.

# What follows was extracted from, and should be in sync with
# https://github.com/ethersphere/bee-clef/tree/master/packaging

DATA_DIR="$1"
CONFIG_DIR="$2"
PASSWORD_FILE=${DATA_DIR}/password
MASTERSEED=${DATA_DIR}/masterseed.json
KEYSTORE=${DATA_DIR}/keystore

echo "ensure-clef-account $DATA_DIR $CONFIG_DIR"

if ! test -f ${PASSWORD_FILE}; then
    < /dev/urandom tr -dc _A-Z-a-z-0-9 2> /dev/null | head -c32 > ${PASSWORD_FILE}
    chmod 0400 ${PASSWORD_FILE}
    echo "Initialized ${PASSWORD_FILE} from /dev/urandom"
fi

if ! test -f ${MASTERSEED}; then
    parse_json() { echo $1|sed -e 's/[{}]/''/g'|sed -e 's/", "/'\",\"'/g'|sed -e 's/" ,"/'\",\"'/g'|sed -e 's/" , "/'\",\"'/g'|sed -e 's/","/'\"---SEPERATOR---\"'/g'|awk -F=':' -v RS='---SEPERATOR---' "\$1~/\"$2\"/ {print}"|sed -e "s/\"$2\"://"|tr -d "\n\t"|sed -e 's/\\"/"/g'|sed -e 's/\\\\/\\/g'|sed -e 's/^[ \t]*//g'|sed -e 's/^"//' -e 's/"$//' ; }
    SECRET=$(cat ${PASSWORD_FILE})
    CLEF="@clefBinary@ --configdir ${DATA_DIR} --keystore ${KEYSTORE} --stdio-ui"
    $CLEF init >/dev/null << EOF
$SECRET
$SECRET
EOF
    $CLEF newaccount >/dev/null << EOF
$SECRET
EOF
    $CLEF setpw 0x$(parse_json $(cat ${KEYSTORE}/*) address) >/dev/null << EOF
$SECRET
$SECRET
$SECRET
EOF
    $CLEF attest $(sha256sum ${CONFIG_DIR}/rules.js | cut -d' ' -f1 | tr -d '\n') >/dev/null << EOF
$SECRET
EOF
    echo "Clef data dir initialized"
fi