#!/bin/bash
# Redis installation script for provisioning system
# This is a template - customize for your needs

set -euo pipefail

REDIS_VERSION="${REDIS_VERSION:-7.2.3}"
REDIS_PORT="${REDIS_PORT:-6379}"
REDIS_CONFIG_FILE="/etc/redis/redis.conf"
REDIS_LOG_DIR="/var/log/redis"
REDIS_DATA_DIR="/var/lib/redis"

echo "Installing Redis ${REDIS_VERSION}..."

# Install Redis
if command -v apt-get >/dev/null 2>&1; then
    # Debian/Ubuntu
    apt-get update
    apt-get install -y redis-server
elif command -v yum >/dev/null 2>&1; then
    # RHEL/CentOS
    yum install -y redis
elif command -v dnf >/dev/null 2>&1; then
    # Fedora
    dnf install -y redis
else
    echo "Unsupported package manager"
    exit 1
fi

# Create directories
mkdir -p "${REDIS_LOG_DIR}" "${REDIS_DATA_DIR}"
chown redis:redis "${REDIS_LOG_DIR}" "${REDIS_DATA_DIR}"

# Configure Redis (basic template)
cat > "${REDIS_CONFIG_FILE}" << EOF
# Redis configuration generated by provisioning system
port ${REDIS_PORT}
bind 127.0.0.1
dir ${REDIS_DATA_DIR}
logfile ${REDIS_LOG_DIR}/redis-server.log
loglevel notice

# Memory management
maxmemory \${REDIS_MAXMEMORY:-256mb}
maxmemory-policy \${REDIS_MAXMEMORY_POLICY:-allkeys-lru}

# Persistence
save 900 1
save 300 10
save 60 10000

# Security
# requirepass \${REDIS_PASSWORD}
EOF

# Enable and start Redis
systemctl enable redis-server || systemctl enable redis
systemctl start redis-server || systemctl start redis

echo "Redis installation completed successfully!"
echo "Port: ${REDIS_PORT}"
echo "Config: ${REDIS_CONFIG_FILE}"
echo "Logs: ${REDIS_LOG_DIR}/redis-server.log"