#!/usr/bin/env bash
set -euo pipefail

# Require root (sudo or doas)
if [ "$(id -u)" -ne 0 ]; then
  echo "Error: this script must be run as root." >&2
  echo "Try: sudo $0 $*" >&2
  echo "  or: doas $0 $*" >&2
  exit 1
fi

# "catch": runs when any command fails
catch() {
  code=$?
  echo "Error on line $1: '$BASH_COMMAND' exited with status $code" >&2
  exit "$code"
}
trap 'catch $LINENO' ERR

# Which user's password to change: whoever invoked sudo/doas
# (plain "passwd" as root would change root's password instead).
TARGET_USER="${SUDO_USER:-${DOAS_USER:-root}}"

# When run as "curl ... | sudo bash", stdin is the script itself, so passwd
# must read from the real terminal (/dev/tty) instead.
if ! : < /dev/tty 2>/dev/null; then
  echo "Error: no terminal available, so passwd cannot prompt for a password." >&2
  echo "Run this from an interactive terminal." >&2
  exit 1
fi

echo "Please enter a new password for user: $TARGET_USER"
passwd "$TARGET_USER" < /dev/tty > /dev/tty 2>&1

# Detach stdin from the rest so nothing can swallow the piped script
echo "System will now update"
apt update < /dev/null
apt upgrade -y < /dev/null
apt autoremove -y < /dev/null

echo "System will now check for flatpak"
if command -v flatpak >/dev/null 2>&1; then
  flatpak update -y < /dev/null
  flatpak uninstall --unused -y < /dev/null
else
  echo "Flatpak is not installed, skipping."
fi

echo "Done."