#!/bin/bash -p

# omarchy:summary=Refresh dnf repository metadata, then update all packages.
# omarchy:requires-sudo=true

if [[ $- != *p* ]]; then
  echo "Refusing an unsafe Bash startup." >&2
  exit 126
fi

security_entrypoint=$(/usr/bin/readlink -e -- "${BASH_SOURCE[0]}") || exit 126
source "${security_entrypoint%/*}/omarchy-security-functions" || exit 126
omarchy_security_require_privileged_bash_startup || exit 126
set -e
omarchy_security_sanitize_bash_environment "$0" "$@"
omarchy_security_require_source_root "$0"
# Channel switching calls this behind its own sanitized PATH and hands the
# caller's original path over the same way the updater receives it.
user_path=${OMARCHY_UPDATE_USER_PATH:-$PATH}
unset OMARCHY_UPDATE_USER_PATH
# Traps first, so a signal or failure during the entry revocation still
# exits through the cleanup path.
omarchy_security_install_sudo_cleanup_traps
omarchy_security_revoke_sudo_timestamp || exit 1
omarchy_security_enable_no_update_sudo

# Historical name: this used to rewrite /etc/pacman.conf from Omarchy's
# dedicated mirrors. On Fedora the system repos live in /etc/yum.repos.d and
# are managed by the distro and install scripts, so this only refreshes
# metadata and upgrades. The channel argument is accepted for compatibility.
channel="${1:-stable}"

if [[ $channel != "stable" && $channel != "rc" && $channel != "edge" ]]; then
  echo "Error: Invalid channel '$channel'. Must be one of: stable, rc, edge"
  exit 1
fi

echo "Setting channel to $channel"
echo

# Allow user customization of /etc/yum.repos.d before the upgrade runs, so
# custom repositories and excludes shape the transaction below. The hook is
# user code: it runs cold behind the no-update wrapper, and the timestamp is
# revoked again afterwards so any authorization the hook obtained for itself
# cannot carry into the transaction.
omarchy_security_revoke_sudo_timestamp
PATH="$OMARCHY_PATH/default/omarchy/sudo-no-update:$user_path" \
  "$OMARCHY_PATH/bin/omarchy-hook" pre-refresh-pacman
omarchy_security_revoke_sudo_timestamp

# Refresh all repo metadata and then update
omarchy-update-dnf dnf upgrade -y --refresh
