#!/bin/sh

LOCKFILE="/redis-lock/redis-cluster-init.lock"

# Start Redis server in the background
redis-server /usr/local/etc/redis/redis.conf &

# Wait for Redis server to start
sleep 5

# Only initialize the cluster if the lock file doesn't exist
if [ ! -f "$LOCKFILE" ]; then
  echo "Initializing Redis Cluster..."

  # Create lock file to prevent further initialization attempts
  touch "$LOCKFILE"
  if [ $? -eq 0 ]; then
    echo "Lock file created successfully at $LOCKFILE."
  else
    echo "Failed to create lock file."
  fi

  # Initialize the Redis cluster
  yes yes | redis-cli --cluster create \
    redis-node-1:6379 \
    redis-node-2:6379 \
    redis-node-3:6379 \
    --cluster-replicas 0

  echo "Redis Cluster initialized."
  
  # Wait for cluster to be fully ready
  echo "Waiting for cluster to be fully operational..."
  sleep 3
else
  echo "Cluster already initialized, skipping initialization."
fi

# Keep the container running
tail -f /dev/null
