#!/usr/bin/env bash
#### ACTUALLY AUTOMATIC UPDATES

set -euo pipefail

# Ensure the running user is actually root
if [ "$(id -u)" -ne 0 ]; then
    echo "Error: This script must be run directly as root." >&2
    exit 1
fi

# 1. Pre-seed debconf so the package activates itself during installation
echo "unattended-upgrades unattended-upgrades/enable_auto_updates boolean true" | debconf-set-selections

# 2. Update package lists and install unattended-upgrades non-interactively
apt-get update
apt-get install -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" unattended-upgrades

# 3. Ensure the daily trigger file exists and is active
dpkg-reconfigure -f noninteractive unattended-upgrades

# 4. Configure origins to allow full upgrades (not just security patches)
cat << 'EOF' > /etc/apt/apt.conf.d/52fully-automatic-origins
Unattended-Upgrade::Origins-Pattern {
    "origin=*";
};

// CRITICAL: This enables true 'dist-upgrade / full-upgrade' behavior
Unattended-Upgrade::Package-Blacklist { };
Unattended-Upgrade::DevRelease "false";
Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::MinimalSteps "false";
Unattended-Upgrade::InstallOnShutdown "false";

// Allow apt to add new dependencies and delete conflicting packages automatically
Unattended-Upgrade::Allow-New-Dependencies "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Remove-New-Unused-Dependencies "true";
EOF

# 5. Trigger a dry-run test to guarantee the syntax is flawless
# unattended-upgrade --dry-run --debug
