#!/bin/bash

# Armbian: apt version. Update the system packages. Keep changed config
# files, as an unattended update cannot answer conffile questions.
# With nala installed, use nala: it downloads in parallel. nala upgrade
# also updates the package lists. --no-full removes no packages.
# After the upgrade, list what it held back and the new default config
# files that it did not install.

set -e

echo -e "\e[32m\nUpdate system packages\e[0m"

confold=(-o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold)
marker=$(mktemp)
trap 'rm -f "$marker"' EXIT

if omarchy-cmd-present nala; then
  sudo DEBIAN_FRONTEND=noninteractive nala upgrade -y --no-full "${confold[@]}"
  full="sudo nala full-upgrade"
else
  sudo apt-get update
  sudo DEBIAN_FRONTEND=noninteractive apt-get -y "${confold[@]}" upgrade --with-new-pkgs
  full="sudo apt full-upgrade"
fi

# An upgrade that removes a package needs a full upgrade.
mapfile -t held < <(apt-get -s dist-upgrade 2>/dev/null | awk '/^Inst / { print $2 }')
if (( ${#held[@]} )); then
  echo -e "\e[33m\nNot upgraded, they need a full upgrade: ${held[*]}"
  echo -e "Check what it removes, then run: $full\e[0m"
fi

# As root: find cannot read some directories in /etc as a user.
mapfile -t kept < <(sudo find /etc -name '*.dpkg-dist' -cnewer "$marker" 2>/dev/null)
if (( ${#kept[@]} )); then
  echo -e "\e[33m\nYour changed config files stay in use. The new defaults are next to them:"
  printf '  %s\n' "${kept[@]}"
  echo -e "\e[0m"
fi
