#!/usr/bin/env bash

# Proxmox VE 8 -> 9 upgrade helper with colored messages
# Requires root. Uses pve8to9 pre-check and updates repos to Debian Trixie and Proxmox VE 9.

set -u

# Require root
if [ "${EUID:-$(id -u)}" -ne 0 ]; then
  echo "This script must be run as root."
  exit 1
fi

# Colors: try tput; fall back to ANSI
if command -v tput >/dev/null 2>&1; then
  RESET="$(tput sgr0)"
  GREEN="$(tput setaf 2 || true)"
  RED="$(tput setaf 1 || true)"
  if [ "$(tput colors 2>/dev/null || echo 0)" -ge 256 ]; then
    ORANGE="$(printf '\033[38;5;214m')"
  else
    ORANGE="$(tput setaf 3 || printf '\033[33m')"
  fi
else
  RESET=$'\033[0m'
  GREEN=$'\033[32m'
  RED=$'\033[31m'
  ORANGE=$'\033[33m'
fi

pause() { echo; sleep 2; }
info()  { printf "%b%s%b\n" "$ORANGE" "$1" "$RESET"; }
ok()    { printf "%b%s%b\n" "$GREEN" "$1" "$RESET"; }
fail()  { printf "%b%s%b\n" "$RED"   "$1" "$RESET"; }

run_cmd() {
  # $1 = start msg (orange), $2 = success msg (green), $3 = fail msg (red), $4... = command
  local start_msg="$1"
  local ok_msg="$2"
  local fail_msg="$3"
  shift 3
  info "$start_msg"
  if "$@"; then
    ok "$ok_msg"
    return 0
  else
    fail "$fail_msg"
    return 1
  fi
}

# 1. Clear screen
clear

# 2. pve8to9 --full with message
CHECK_LOG="/root/pve8to9-full.$(date +%F-%H%M%S).log"
info "Checking Proxmox VE if it is ready to Upgrade."
if ! command -v pve8to9 >/dev/null 2>&1; then
  fail "pve8to9 is not available. Ensure Proxmox VE 8.4 is fully up-to-date."
  exit 1
fi
# Run the full checker and capture output
if ! pve8to9 --full | tee "$CHECK_LOG"; then
  fail "pve8to9 execution failed."
  exit 1
fi

# 3-4. If warnings > 0, stop and show them (red); else continue (green)
# Match lines starting with WARN or WARNING
WARN_LINES="$(grep -E '^(WARN|WARNING)' "$CHECK_LOG" || true)"
WARN_COUNT="$(printf "%s\n" "$WARN_LINES" | sed '/^[[:space:]]*$/d' | wc -l)"
if [ "${WARN_COUNT:-0}" -gt 0 ]; then
  fail "Found ${WARN_COUNT} Warning(s). Upgrade check failed. See below:"
  # print each warning in red
  while IFS= read -r line; do
    [ -n "$line" ] && fail "$line"
  done <<< "$WARN_LINES"
  exit 1
else
  ok "Proxmox VE is Ready to Upgrade."
fi
pause

# 5-6. apt update
if ! run_cmd "Checking for updates of the existed repository." \
             "Checking updates COMPLETED." \
             "Checking Updates Failed." \
             apt update; then
  exit 1
fi
pause

# 7-8. apt dist-upgrade
if ! run_cmd "Installing updates of the existed repository." \
             "Installing updates COMPLETED." \
             "Installing Updates Failed." \
             env DEBIAN_FRONTEND=noninteractive apt -y dist-upgrade; then
  exit 1
fi
pause

# 9. pveversion
info "Showing Proxmox VE version (pveversion):"
if pveversion; then
  :
else
  fail "Failed to query Proxmox VE version."
  exit 1
fi
pause

# 10. Update Debian Base Repositories to Trixie
info "Update Debian Base Repositories to Trixie"

# 11-12. sed replacements; tolerate missing files but fail if all change attempts fail unexpectedly
files_changed=0
for f in /etc/apt/sources.list /etc/apt/sources.list.d/pve-enterprise.list; do
  if [ -f "$f" ]; then
    if sed -i 's/bookworm/trixie/g' "$f"; then
      files_changed=$((files_changed+1))
    fi
  fi
done

if [ "$files_changed" -ge 1 ]; then
  ok "Update Debian Base Repositories to Trixie COMPLETED."
else
  # If neither file existed nor changed, still proceed, as .sources may already be in use
  ok "No legacy Bookworm entries found to update; continuing."
fi
pause

# 13-15. Add the Proxmox VE 9 Package Repository (no-subscription)
info "Add the Proxmox VE 9 Package Repository"
mkdir -p /etc/apt/sources.list.d
if cat > /etc/apt/sources.list.d/proxmox.sources <<'EOF'
Types: deb
URIs: http://download.proxmox.com/debian/pve
Suites: trixie
Components: pve-no-subscription
Signed-By: /usr/share/keyrings/proxmox-archive-keyring.gpg
EOF
then
  ok "Adding Proxmox VE 9 Package Repository COMPLETED."
else
  fail "Adding Proxmox VE 9 Package Repository Failed."
  exit 1
fi
pause

# 16-18. Update the Ceph Package Repository (no-subscription, Squid on Trixie)
info "Update the Ceph Package Repository"
if cat > /etc/apt/sources.list.d/ceph.sources <<'EOF'
Types: deb
URIs: http://download.proxmox.com/debian/ceph-squid
Suites: trixie
Components: no-subscription
Signed-By: /usr/share/keyrings/proxmox-archive-keyring.gpg
EOF
then
  ok "Updating Ceph Package Repository COMPLETED."
else
  fail "Updating Ceph Package Repository Failed."
  exit 1
fi
pause

# 19-20. Refresh Package Index
if ! run_cmd "Refresh Package Index" \
             "Checking updates for Proxmox VE 9 COMPLETED." \
             "Checking updates for Proxmox VE 9 Failed." \
             apt update; then
  exit 1
fi
pause

# 21-22. Upgrade the system to Debian Trixie and Proxmox VE 9.0
if ! run_cmd "Upgrade the system to Debian Trixie and Proxmox VE 9.0" \
             "Upgrading the system to Debian Trixie and Proxmox VE 9.0 COMPLETED." \
             "Upgrading the system to Debian Trixie and Proxmox VE 9.0 Failed." \
             env DEBIAN_FRONTEND=noninteractive apt -y dist-upgrade; then
  exit 1
fi

exit 0
