#!/bin/bash

# omarchy:summary=Update Omarchy and system packages
# omarchy:args=[-y]
# omarchy:examples=omarchy update | omarchy update -y
# omarchy:requires-sudo=true

set -e

if [[ -z ${OMARCHY_UPDATE_LOGGED:-} ]]; then
  script_command=$(printf '%q ' "$0" "$@")
  exec env OMARCHY_UPDATE_LOGGED=1 script -qefc "$script_command" "/tmp/omarchy-update.log"
fi

if ! omarchy-update-lock held; then
  exec omarchy-update-lock run "$0" "$@"
fi

trap 'echo ""; echo -e "\033[0;31mSomething went wrong during the update!\n\nPlease review the output above carefully, correct the error, and retry the update.\n\nIf you need assistance, get help from the community at https://omarchy.org/discord\033[0m"' ERR
trap 'omarchy-update-stay-awake stop' EXIT

omarchy-update-requires-free-space

# -y is a promise not to ask anything. Steps that would need an answer report
# and move on instead of waiting on a prompt nobody is here to give.
[[ ${1:-} != "-y" ]] || export OMARCHY_UPDATE_UNATTENDED=1

if [[ ${1:-} == "-y" ]] || omarchy-update-confirm; then
  # Before the snapshot: the cache is on the snapshotted subvolume, so pruning
  # after it frees nothing until that snapshot ages out.
  omarchy-update-pkg-prune

  # 127 means Snapper is deliberately absent. Any other failure already said
  # what went wrong, and a missing snapshot is not worth blocking an update
  # over, but it must not pass for one either.
  omarchy-snapshot create || (($? == 127)) ||
    echo -e "\e[33mContinuing the update without a snapshot.\e[0m" >&2

  omarchy-update-stay-awake start

  omarchy-update-dev
  omarchy-update-keyring

  # Migrations ship with the packages installed here and are written against
  # them, so everything below waits on this finishing. An upgrade that stopped
  # takes the update with it rather than migrating against what is still on disk.
  omarchy-update-system-pkgs
  omarchy-migrate
  omarchy-hook post-update
  omarchy-update-aur-pkgs
  omarchy-update-mise
  omarchy-update-orphan-pkgs

  omarchy-update-analyze-logs
  omarchy-update-status

  # Release update-owned inhibitors before offering a reboot. A confirmed
  # reboot can terminate this process before its EXIT trap gets a chance to
  # remove the persistent Stay Awake marker.
  omarchy-update-stay-awake stop
  trap - EXIT

  omarchy-update-restart
fi
