#!/bin/bash
set -euo pipefail

show_help() {
	cat <<'EOF'
Usage: fullupgrade

Updates Arch Linux and performs cleanup:
  - updates archlinux-keyring
  - performs a full system synchronization
  - removes orphaned packages
  - cleans the pacman cache

Warning: this script modifies the system and runs without confirmation.
EOF
}


require_root() {
	if [ "${EUID:-$(id -u)}" -ne 0 ]; then
		echo "Error: this script must be run as root." >&2
		exit 1
	fi
}

cleanup_orphans() {
	local orphans=()

	mapfile -t orphans < <(pacman -Qqtd)

	if [ "${#orphans[@]}" -gt 0 ]; then
		pacman -Rns --noconfirm "${orphans[@]}"
	else
		echo "No orphaned packages to remove."
	fi
}

main() {
	if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
		show_help
		exit 0
	fi

	require_root

	echo "Updating archlinux-keyring..."
	pacman -Sy --noconfirm archlinux-keyring

	echo "Performing full system update..."
	pacman -Syu --noconfirm

	echo "Searching for orphaned packages..."
	cleanup_orphans

	echo "Cleaning pacman cache..."
	pacman -Sc --noconfirm

	echo "Update completed successfully."
}

main "$@"
