#!/usr/bin/env bash

# Install KSM (Kernel Samepage Merging) systemd service
# This improves memory efficiency on systems running multiple similar containers

echo "Installing KSM (Kernel Samepage Merging) service..."

# Check if service already exists
if systemctl list-unit-files | grep -q "^ksm.service"; then
    echo "KSM service already exists, updating configuration..."
    systemctl stop ksm.service 2>/dev/null || true
fi

# Create the systemd service file
cat > /etc/systemd/system/ksm.service << 'EOF'
[Unit]
Description=Kernel Samepage Merging
DefaultDependencies=false
After=sysinit.target local-fs.target
Before=basic.target

[Service]
Type=oneshot
ExecStart=/bin/sh -c 'echo 1 > /sys/kernel/mm/ksm/run'
ExecStart=/bin/sh -c 'echo 400 > /sys/kernel/mm/ksm/pages_to_scan'
ExecStart=/bin/sh -c 'echo 10 > /sys/kernel/mm/ksm/sleep_millisecs'
RemainAfterExit=true

[Install]
WantedBy=multi-user.target
EOF

# Set proper permissions
chmod 644 /etc/systemd/system/ksm.service

# Reload systemd and enable the service
systemctl daemon-reload
systemctl enable ksm.service

# Start the service
if systemctl start ksm.service; then
    echo "✓ KSM service installed and started successfully"
    
    # Verify KSM is running
    if [ -f /sys/kernel/mm/ksm/run ] && [ "$(cat /sys/kernel/mm/ksm/run)" = "1" ]; then
        echo "✓ KSM is active and running"
        echo "  - Pages to scan: $(cat /sys/kernel/mm/ksm/pages_to_scan)"
        echo "  - Sleep milliseconds: $(cat /sys/kernel/mm/ksm/sleep_millisecs)"
    else
        echo "⚠ KSM service started but KSM is not active"
    fi
else
    echo "✗ Failed to start KSM service"
    exit 1
fi

echo ""
echo "KSM (Kernel Samepage Merging) has been installed and configured."
echo "This will help reduce memory usage when running multiple similar containers."