#!/bin/bash
# force-recreate.sh — recreate one node's compose services (keeps volumes).
# Runs peer-capture (.before-stop) before and peer-reinject (.after-start) after
# so EL peer sets survive the restart (lisk-class --disable-discovery fix).

if [ -z "$1" ] || [ ! -f "/root/rpc/$1.yml" ]; then
    echo "Error: Either no argument provided or /root/rpc/$1.yml does not exist."
    exit 1
fi

COMPOSE_PATH="$1"
BASEPATH="/root/rpc"
cd "$BASEPATH" || exit 1

run_hook() {
    local kind="$1"   # before-stop | after-start
    local generic="$2"
    if [ -f "${BASEPATH}/${COMPOSE_PATH}.${kind}" ]; then
        /bin/bash "${BASEPATH}/${COMPOSE_PATH}.${kind}" || \
            echo "WARN: ${COMPOSE_PATH}.${kind} exited $?" >&2
    elif [ -x "${BASEPATH}/${generic}" ]; then
        "${BASEPATH}/${generic}" "$COMPOSE_PATH" || \
            echo "WARN: ${generic} exited $?" >&2
    fi
}

run_hook before-stop peer-capture.sh

docker compose up -d --force-recreate $(cat "/root/rpc/${COMPOSE_PATH}.yml" | yaml2json - | jq '.services' | jq -r 'keys[]' | tr '\n' ' ')

run_hook after-start peer-reinject.sh
