#!/bin/bash -e
# Configure automatic security updates for Dangerous Pi
# Installs and configures unattended-upgrades for Debian security patches only

echo "=== Setting up automatic security updates ==="

# Configure unattended-upgrades for security-only updates
echo "Writing unattended-upgrades configuration..."
cat > /etc/apt/apt.conf.d/50unattended-upgrades << 'UUEOF'
// Dangerous Pi - Automatic Security Updates Configuration
// Only install security updates automatically

Unattended-Upgrade::Origins-Pattern {
    "origin=Debian,codename=${distro_codename},label=Debian-Security";
    "origin=Debian,codename=${distro_codename}-security,label=Debian-Security";
};

// Remove unused kernel-related packages after upgrade
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";

// Remove unused auto-installed dependencies
Unattended-Upgrade::Remove-Unused-Dependencies "true";

// Automatically fix interrupted dpkg runs
Unattended-Upgrade::AutoFixInterruptedDpkg "true";

// Do NOT automatically reboot - user controls this via the web UI
Unattended-Upgrade::Automatic-Reboot "false";

// Limit download speed to reduce SD card wear and bandwidth usage (KB/s)
Acquire::http::Dl-Limit "256";
UUEOF

# Configure APT periodic updates
echo "Writing APT periodic configuration..."
cat > /etc/apt/apt.conf.d/20auto-upgrades << 'APEOF'
// Dangerous Pi - APT Periodic Update Schedule
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
APEOF

# Enable the unattended-upgrades service
echo "Enabling unattended-upgrades service..."
systemctl enable unattended-upgrades

echo ""
echo "=== Automatic Security Updates Configuration Complete ==="
echo ""
echo "Security-only updates will install automatically (daily check)."
echo "Automatic reboots are DISABLED - use the web UI to reboot when needed."
echo ""
echo "To disable automatic updates:"
echo "  Set AUTO_SECURITY_UPDATES=false in /opt/dangerous-pi/.env"
echo ""
