#
# Cookbook:: irrigate-orchard_base
# Recipe:: unattended_upgrade
#
# This recipe manages installing unattended upgrades and constrains both
# apt-daily (package-list refresh) and apt-daily-upgrade (the actual upgrade)
# timers to a narrow UTC window so they don't hold the dpkg lock during
# chef-client runs or kitchen tests.

if platform_family?('debian')

  execute 'systemd-daemon-reload' do
    command 'systemctl daemon-reload'
    action :nothing
  end

  # --- apt-daily.timer override (package-list refresh) ---
  directory '/etc/systemd/system/apt-daily.timer.d' do
    owner 'root'
    group 'root'
    mode '0755'
  end

  file '/etc/systemd/system/apt-daily.timer.d/schedule-override.conf' do
    content <<~INI
      [Timer]
      OnCalendar=
      OnCalendar=#{node['unattended_upgrades']['apt_daily_oncalendar']}
      RandomizedDelaySec=#{node['unattended_upgrades']['apt_daily_randomized_delay']}
      Persistent=true
    INI
    owner 'root'
    group 'root'
    mode '0644'
    notifies :run, 'execute[systemd-daemon-reload]', :immediately
  end

  # --- apt-daily-upgrade.timer override (actual upgrade run) ---
  directory '/etc/systemd/system/apt-daily-upgrade.timer.d' do
    owner 'root'
    group 'root'
    mode '0755'
  end

  file '/etc/systemd/system/apt-daily-upgrade.timer.d/schedule-override.conf' do
    content <<~INI
      [Timer]
      OnCalendar=
      OnCalendar=#{node['unattended_upgrades']['apt_upgrade_oncalendar']}
      RandomizedDelaySec=#{node['unattended_upgrades']['apt_upgrade_randomized_delay']}
      OnBootSec=#{node['unattended_upgrades']['apt_upgrade_on_boot_delay']}
      Persistent=true
    INI
    owner 'root'
    group 'root'
    mode '0644'
    notifies :run, 'execute[systemd-daemon-reload]', :immediately
  end

  packages = %w(
    unattended-upgrades
    apt-listchanges
  )

  packages.each do |item|
    package item
  end

  template '/etc/apt/apt.conf.d/50unattended-upgrades' do
    source 'unattended-upgrades.erb'
    owner 'root'
    group 'root'
    mode '0644'
  end

  template '/etc/apt/apt.conf.d/20auto-upgrades' do
    source 'auto-upgrades.erb'
    owner 'root'
    group 'root'
    mode '0644'
  end
end
