#!/bin/bash
set -e

echo "Stopping Redis service..."
sudo systemctl stop redis-server

echo "Creating Redis configuration file..."
sudo bash -c 'cat > /etc/redis/redis.conf << EOF
bind 0.0.0.0
protected-mode no
port 6379
dir /mnt/k8s/redis
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec
save 900 1
save 300 10
save 60 10000
EOF'

echo "Setting permissions for Redis configuration..."
sudo chown redis:redis /etc/redis/redis.conf
sudo chmod 640 /etc/redis/redis.conf

echo "Creating symbolic links to Redis data files..."
sudo ln -sf /mnt/k8s/redis/appendonlydir/appendonly.aof.149903.base.rdb /mnt/k8s/redis/dump.rdb
sudo ln -sf /mnt/k8s/redis/appendonlydir/appendonly.aof.149903.incr.aof /mnt/k8s/redis/appendonly.aof

echo "Updating systemd service file..."
sudo sed -i '/ReadWritePaths=-\/mnt\/k8s\/redis/a ReadWritePaths=-\/mnt\/k8s\/redis\/appendonlydir' /etc/systemd/system/redis-server.service

echo "Reloading systemd and restarting Redis..."
sudo systemctl daemon-reload
sudo systemctl restart redis-server
sleep 5

echo "Checking Redis data..."
sudo redis-cli dbsize
sudo redis-cli keys '*' | head -5
