# Create a local file with the Redis installation script
resource "local_file" "redis_install_script" {
  filename = "${path.module}/tmp/install_redis.sh"
  content  = <<-EOT
#!/bin/bash
set -e

echo "Installing Redis..."
sudo apt-get update
sudo apt-get install -y redis-server

# Stop Redis before configuration
echo "Stopping Redis service..."
sudo systemctl stop redis-server

# Configure Redis
sudo chown redis:redis /mnt/k8s/redis
echo "Configuring Redis..."

# Find and copy the latest RDB and AOF files from Bitnami directory
echo "Finding and copying latest Redis data files..."
LATEST_RDB=$(sudo find /mnt/k8s/redis/appendonlydir -name "*.base.rdb" | sort -V | tail -1)
LATEST_AOF=$(sudo find /mnt/k8s/redis/appendonlydir -name "*.incr.aof" | sort -V | tail -1)

# Create a backup directory
BACKUP_DIR="/mnt/k8s/redis/backup_$(date +%Y%m%d%H%M%S)"
sudo mkdir -p "$BACKUP_DIR"

# Backup existing files
if [ -f "/mnt/k8s/redis/dump.rdb" ]; then 
  sudo mv "/mnt/k8s/redis/dump.rdb" "$BACKUP_DIR/"
fi

if [ -f "/mnt/k8s/redis/appendonly.aof" ]; then 
  sudo mv "/mnt/k8s/redis/appendonly.aof" "$BACKUP_DIR/"
fi

# Copy the latest files
echo "Copying $LATEST_RDB to /mnt/k8s/redis/dump.rdb"
sudo cp "$LATEST_RDB" "/mnt/k8s/redis/dump.rdb"
echo "Copying $LATEST_AOF to /mnt/k8s/redis/appendonly.aof"
sudo cp "$LATEST_AOF" "/mnt/k8s/redis/appendonly.aof"

# Set permissions
sudo chown redis:redis "/mnt/k8s/redis/dump.rdb"
sudo chown redis:redis "/mnt/k8s/redis/appendonly.aof"
sudo chmod 640 "/mnt/k8s/redis/dump.rdb"
sudo chmod 640 "/mnt/k8s/redis/appendonly.aof"

# Create Redis configuration
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
aof-use-rdb-preamble yes
aof-load-truncated yes
aof-rewrite-incremental-fsync yes
EOF'

# Update systemd service file to allow access to appendonlydir
if ! sudo grep -q "ReadWritePaths=-/mnt/k8s/redis/appendonlydir" /etc/systemd/system/redis-server.service; then
  sudo sed -i '/ReadWritePaths=-\/mnt\/k8s\/redis/a ReadWritePaths=-\/mnt\/k8s\/redis\/appendonlydir' /etc/systemd/system/redis-server.service || true
fi

# Ensure proper permissions
sudo chown redis:redis /etc/redis/redis.conf
sudo chmod 640 /etc/redis/redis.conf
sudo chown -R redis:redis /mnt/k8s/redis
sudo chmod -R 750 /mnt/k8s/redis

# Reload systemd and restart Redis
sudo systemctl daemon-reload
sudo systemctl restart redis-server
echo "Waiting for Redis to start..."
sleep 5
sudo systemctl status redis-server --no-pager || true

# Verify Redis data was loaded
echo "Checking Redis data..."
sudo redis-cli dbsize
sudo redis-cli keys '*' | head -5 || true
echo "Redis installation completed!"
EOT

  file_permission = "0755"
}

# Create the scripts directory if it doesn't exist
resource "null_resource" "create_scripts_dir" {
  provisioner "local-exec" {
    command = "mkdir -p ${path.module}/scripts"
  }
}

# Upload and execute the Redis installation script
resource "ssh_resource" "redis_install" {
  depends_on = [local_file.redis_install_script, null_resource.create_scripts_dir]
  
  host        = local.ssh_host
  user        = local.ssh_user
  port        = local.ssh_port
  private_key = local.ssh_private_key
  timeout     = "5m"

  when = "create"

  file {
    source      = local_file.redis_install_script.filename
    destination = "/tmp/install_redis.sh"
    permissions = "0755"
  }

  commands = [
    "bash /tmp/install_redis.sh"
  ]
}
