#!/bin/bash
ETAT_PRECEDENT_FICHIER="/tmp/dernier_role_connu"
ROLE=$(./verifier_role_db.sh)
ROLE_PRECEDENT=$(cat "$ETAT_PRECEDENT_FICHIER" 2>/dev/null || echo "inconnu")
BOT_TOURNE=$(docker ps -q -f name=bot-discord)

if [ "$ROLE" != "$ROLE_PRECEDENT" ]; then
    echo "$(date '+%Y-%m-%d %H:%M:%S') - changement de role : $ROLE_PRECEDENT -> $ROLE" >> /var/log/kuby-bascule.log
fi
echo "$ROLE" > "$ETAT_PRECEDENT_FICHIER"

if [ "$ROLE" = "primary" ] && [ -z "$BOT_TOURNE" ]; then
    docker start bot-discord
fi

if [ "$ROLE" = "replica" ] && [ -n "$BOT_TOURNE" ]; then
    docker stop bot-discord
fi
