#!/bin/sh -e
#
# aptup - apt update/upgrade/autoremove

# run updates in the background, so they should slow me down
BACKGROUND="ionice -c 3 -t nice"

os="$(uname -s)"
if [ "${os}" != "Linux" ]; then
  printf '%s\n' "${os} not linux"
  exit 1
fi

# apt | debian
# shellcheck disable=SC2250
if command -v apt >/dev/null 2>&1; then
  start_time=$(date '+%s')

  sudo apt --fix-broken install
  sudo apt-get --fix-missing install
  sudo apt update && sudo apt full-upgrade -y
  ${BACKGROUND} sudo apt-get autoremove --yes
  ${BACKGROUND} sudo apt-get autoremove --purge --yes
  ${BACKGROUND} sudo apt-get update --yes
  # apt list --upgradable 2>/dev/null | grep -c upgradable
  ${BACKGROUND} sudo apt-get upgrade --yes
  ${BACKGROUND} sudo apt-get autoclean --yes
  ${BACKGROUND} sudo apt-get dist-upgrade

  # pipx
  if command -v pipx >/dev/null 2>&1; then
    pipx upgrade-all
  fi

  # uv
  if command -v uv >/dev/null 2>&1; then
    uv self update 2>/dev/null
    uv tool upgrade --all
  fi

  end_time=$(date '+%s')
  elapsed=$(echo "$end_time - $start_time" | bc)
  printf '%s\n' "time elapsed: $elapsed seconds"
fi

# apk | alpine linux
if command -v apk >/dev/null 2>&1; then
  # update
  { set +o xtrace; } 2>/dev/null
  printf 'updating Alpine Linux repositories...\n' >&2
  set -o xtrace
  command apk update --verbose --progress
  command apk upgrade --verbose --progress

  # update, repair everything
  { set +o xtrace; } 2>/dev/null
  printf -- 'updating...\n' >&2
  set -o xtrace
  command apk update --verbose --verbose --progress

  { set +o xtrace; } 2>/dev/null
  printf -- 'upgrading...\n' >&2
  set -o xtrace
  command apk upgrade --verbose --verbose --progress

  { set +o xtrace; } 2>/dev/null
  printf -- 'repairing and resolving dependencies...\n' >&2
  set -o xtrace
  command apk fix --verbose --verbose --depends --progress

  { set +o xtrace; } 2>/dev/null
  printf -- 'verifying installations...\n' >&2
  set -o xtrace
  command apk verify --verbose --verbose --progress
fi

# done
{ set +o xtrace; } 2>/dev/null
exit
