#!/usr/bin/env bash
# bluerune-updates: which Arch Linux this system updates to (PLAN.md, Phase 13).
#
# BlueRune's stable channel holds all of Arch at a date it was tested with, and moves the
# date only once BlueRune passes its tests there; the edge channel follows Arch as it is.
# /etc/bluerune/updates.conf says which channel, and whether to hold at its date:
#
#   channel = stable     # or edge
#   hold = true          # false: follow Arch directly, untested
#
# pacman's [core], [extra] and [multilib] take their servers from /etc/pacman.d/bluerune-arch,
# which this writes: the snapshot of the channel's date (https://pkgs.bluerune.dev/arch/<date>/),
# or, not held, an Include of the system's own /etc/pacman.d/mirrorlist. The date comes from
# https://pkgs.bluerune.dev/<channel>/arch-date; when that can't be read the file stays as
# it is, so it is never left empty. A pacman hook refreshes it after every transaction and a
# timer every few hours, so a newly tested date is there for the next update.
#
#   bluerune-updates status          what this system follows, and what is tested
#   bluerune-updates hold on|off [--channel edge|stable]
#                                    hold Arch at the tested date, or follow Arch directly (root)
#   bluerune-updates refresh         write /etc/pacman.d/bluerune-arch from the channel (root)
#   bluerune-updates check-hyprland  warn if the transaction's Hyprland is newer than tested
#                                    (pacman's hook runs it; it never fails)
set -euo pipefail

CONF=${BLUERUNE_UPDATES_CONF:-/etc/bluerune/updates.conf}
LIST=${BLUERUNE_ARCH_LIST:-/etc/pacman.d/bluerune-arch}
PACMAN_CONF=${BLUERUNE_PACMAN_CONF:-/etc/pacman.conf}
TESTED=${BLUERUNE_TESTED_HYPRLAND:-/usr/share/bluerune/tested-hyprland}
PKGS_URL=${BLUERUNE_PKGS_URL:-https://pkgs.bluerune.dev}
readonly SNAPSHOTS=$PKGS_URL/arch
# The line the file's date is read back from.
readonly DATE_KEY='# bluerune-arch-date ='

if [[ -t 1 ]]; then B=$'\e[1m' Y=$'\e[33m' N=$'\e[0m'; else B='' Y='' N=''; fi
say() { printf '%s\n' "$*"; }
die() { printf 'bluerune-updates: %s\n' "$*" >&2; exit 1; }

usage() { sed -n '18,24s/^# \{0,1\}//p' "${BASH_SOURCE[0]}"; }

# Reading --------------------------------------------------------------------------------

# conf_value <file> <key>: the value of "key = value" in the file (the last one), or nothing.
conf_value() {
    [[ -r $1 ]] || return 0
    awk -v key="$2" -F= '
        /^[[:space:]]*#/ { next }
        { k = $1; gsub(/[[:space:]]/, "", k) }
        k == key { v = substr($0, index($0, "=") + 1); gsub(/^[[:space:]]+|[[:space:]]+$/, "", v); found = v }
        END { if (found != "") print found }' "$1"
}

# channel: the conf's channel; stable unless it names another there is.
channel() {
    local value
    value=$(conf_value "$CONF" channel)
    case $value in edge | stable) say "$value" ;; *) say stable ;; esac
}

# holding: the conf holds Arch at the channel's date (the default) or not.
holding() {
    local value
    value=$(conf_value "$CONF" hold)
    [[ ${value,,} != false && ${value,,} != no && ${value,,} != off ]]
}

# is_date <value>: a YYYY-MM-DD date.
is_date() { [[ $1 =~ ^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$ ]]; }

# list_date <file>: the date a mirror list written here says, "live", or nothing.
list_date() {
    [[ -r $1 ]] || return 0
    sed -n "s/^$DATE_KEY \(.*\)$/\1/p" "$1" | head -n1
}

# usable <file>: a list pacman can take servers from.
usable() { [[ -r $1 ]] && grep -qE '^[[:space:]]*(Server|Include)[[:space:]]*=' "$1"; }

# Writing --------------------------------------------------------------------------------

# conf_text <channel> <true|false>: updates.conf as this and Settings write it.
conf_text() {
    cat <<EOF
# BlueRune's updates (bluerune-updates). channel: the BlueRune channel whose tested Arch date
# is followed (stable or edge). hold: true keeps all of Arch at that date, moved on once
# BlueRune is tested with a newer one; false follows Arch directly, untested.
channel = $1
hold = $2
EOF
}

# list_text <date|live> <channel> [<note>]: /etc/pacman.d/bluerune-arch for the date.
list_text() {
    local date=$1 channel=$2 note=${3:-}
    if [[ $date == live ]]; then
        cat <<EOF
# BlueRune: Arch Linux as it is now, from your own mirrors (not held at a tested date).
# Written by bluerune-updates from /etc/bluerune/updates.conf (channel $channel${note:+; $note}).
$DATE_KEY live
Include = /etc/pacman.d/mirrorlist
EOF
    else
        cat <<EOF
# BlueRune: Arch Linux as it was on $date, the date BlueRune's $channel channel is tested with.
# Written by bluerune-updates from $PKGS_URL/$channel/arch-date${note:+ ($note)}; changes here are
# replaced. To follow Arch directly instead: sudo bluerune-updates hold off
$DATE_KEY $date
Server = $SNAPSHOTS/$date/\$repo/os/\$arch
EOF
    fi
}

# fetch_date <channel>: the channel's arch-date ("YYYY-MM-DD" or "live"); fails when it
# can't be read or says something else.
fetch_date() {
    local value
    value=$(curl -fsSL --max-time 10 --retry 1 "$PKGS_URL/$1/arch-date" 2>/dev/null) || return 1
    value=${value//[[:space:]]/}
    [[ $value == live ]] || is_date "$value" || return 1
    say "$value"
}

# wanted_date <holding 0|1> <channel date or ""> <current date or "">: the date to write,
# or nothing to keep the file as it is.
wanted_date() {
    local hold=$1 fetched=$2 current=$3
    if ((!hold)); then say live; return 0; fi
    if [[ -n $fetched ]]; then say "$fetched"; return 0; fi
    # Not readable: what is there stays; with nothing there, the system's own mirrors.
    [[ -n $current ]] || say live
}

# write_list <text>: the file replaced whole, never half-written.
write_list() {
    local dir tmp
    dir=$(dirname "$LIST")
    mkdir -p "$dir"
    tmp=$(mktemp "$dir/.bluerune-arch.XXXXXX")
    printf '%s\n' "$1" >"$tmp"
    chmod 644 "$tmp"
    mv -f "$tmp" "$LIST"
}

# refresh [--hook|--quiet]
refresh() {
    local mode=${1:-} channel hold=1 fetched='' current want note=''
    channel=$(channel)
    holding || hold=0
    current=$(list_date "$LIST")
    usable "$LIST" || current=''
    if ((hold)); then
        fetched=$(fetch_date "$channel") || fetched=''
    fi
    want=$(wanted_date "$hold" "$fetched" "$current")
    if [[ -z $want ]]; then
        [[ $mode == --quiet || $mode == --hook ]] || say "Couldn't read $PKGS_URL/$channel/arch-date; $LIST stays at $current."
        return 0
    fi
    ((hold)) && [[ -z $fetched ]] && note="the channel couldn't be read; until it can"
    if [[ $want == "$current" ]]; then
        [[ -n $mode ]] || say "Arch: $(describe "$want") (unchanged)."
        return 0
    fi
    write_list "$(list_text "$want" "$channel" "$note")"
    case $mode in
        --quiet) ;;
        --hook)
            [[ -z $current ]] && return 0
            say "${B}BlueRune:${N} Arch is now $(describe "$want") (was $(describe "$current"))."
            say "  Run ${B}sudo pacman -Syu${N} again to update to it." ;;
        *) say "Arch: $(describe "$want")${current:+ (was $(describe "$current"))}." ;;
    esac
}

# describe <date|live>
describe() { if [[ $1 == live ]]; then say "followed directly (not held)"; else say "held at $1"; fi; }

# Hyprland -------------------------------------------------------------------------------

# upstream_version <pacman version>: without epoch's pkgrel, e.g. 1:0.57.2-1 -> 1:0.57.2.
upstream_version() { say "${1%-*}"; }

# hyprland_warning <new version> <tested version>: the warning, when new is a later Hyprland.
hyprland_warning() {
    local new=$1 tested=$2
    [[ -n $new && -n $tested ]] || return 0
    (($(vercmp "$(upstream_version "$new")" "$(upstream_version "$tested")") > 0)) || return 0
    cat <<EOF
${Y}${B}==> BlueRune: Hyprland $(upstream_version "$new") hasn't been tested with BlueRune yet${N}
    BlueRune is tested with Hyprland $(upstream_version "$tested"). Hyprland changes its config and IPC
    between releases, so parts of the desktop (the bar, shortcuts, window rules, Settings)
    may misbehave until BlueRune is updated for it. To stay on tested versions, hold Arch at
    BlueRune's tested date: sudo bluerune-updates hold on (Settings > Updates, "Follow Arch
    directly" off). This update goes ahead.
EOF
}

# tested_version: the Hyprland BlueRune is tested with, or nothing.
tested_version() { [[ -r $TESTED ]] && tr -d '[:space:]' <"$TESTED"; return 0; }

check_hyprland() {
    local tested new
    tested=$(tested_version)
    new=$(LC_ALL=C pacman -Si hyprland 2>/dev/null | awk -F' *: ' '$1 == "Version" { print $2; exit }') || new=''
    hyprland_warning "$new" "$tested" || true
}

# Status ---------------------------------------------------------------------------------

# pacman_uses_list: the sections of pacman.conf that take their servers from the list.
pacman_uses_list() {
    awk -v list="$LIST" '
        /^[[:space:]]*\[[^]]+\]/ { section = $0; gsub(/[][[:space:]]/, "", section); next }
        /^[[:space:]]*Include[[:space:]]*=/ { v = substr($0, index($0, "=") + 1); gsub(/[[:space:]]/, "", v); if (v == list) print section }
    ' "$PACMAN_CONF" 2>/dev/null | paste -sd' '
}

status() {
    local channel current fetched tested installed sections
    channel=$(channel)
    current=$(list_date "$LIST")
    say "Channel:     $channel ($(holding && say "hold = true" || say "hold = false"))"
    say "Arch:        $(describe "${current:-live}")${current:+ ($LIST)}"
    if fetched=$(fetch_date "$channel"); then
        if [[ $fetched == "$current" ]]; then say "Tested date: $fetched (the channel's; this system has it)"
        else say "Tested date: $fetched (the channel's; the next update moves to it)"; fi
    else
        say "Tested date: unknown ($PKGS_URL/$channel/arch-date can't be read)"
    fi
    tested=$(tested_version)
    installed=$(pacman -Q hyprland 2>/dev/null | awk '{ print $2 }') || installed=''
    say "Hyprland:    ${installed:-not installed}${tested:+ (BlueRune is tested with $tested)}"
    sections=$(pacman_uses_list)
    if [[ -n $sections ]]; then say "pacman:      $sections from $LIST"
    else say "pacman:      $PACMAN_CONF doesn't use $LIST; nothing here changes what pacman installs"; fi
}

# hold <on|off> [--channel edge|stable]
hold() {
    local to channel
    case ${1:-} in
        on) to=true ;;
        off) to=false ;;
        *) die "hold takes on or off" ;;
    esac
    channel=$(channel)
    case ${2:-} in
        '') ;;
        --channel)
            case ${3:-} in edge | stable) channel=$3 ;; *) die "--channel takes edge or stable" ;; esac ;;
        *) die "unknown option $2" ;;
    esac
    ((EUID == 0)) || die "run it as root: sudo bluerune-updates hold $1"
    mkdir -p "$(dirname "$CONF")"
    local tmp
    tmp=$(mktemp "$(dirname "$CONF")/.updates.conf.XXXXXX")
    conf_text "$channel" "$to" >"$tmp"
    chmod 644 "$tmp"
    mv -f "$tmp" "$CONF"
    refresh
    if [[ $to == true ]]; then
        say "Packages newer than the tested date stay until Arch's date passes them; to go back to the tested versions now: sudo pacman -Syuu"
    else
        say "Following Arch directly: updates are no longer held for BlueRune's tests; pacman warns when Hyprland moves past the tested version."
    fi
}

main() {
    case ${1:-} in
        status) status ;;
        hold) shift; hold "$@" ;;
        refresh)
            ((EUID == 0)) || [[ -w $(dirname "$LIST") ]] || die "run it as root: sudo bluerune-updates refresh"
            refresh "${2:-}" ;;
        check-hyprland) check_hyprland; return 0 ;;
        -h | --help | '') usage ;;
        *) usage >&2; exit 2 ;;
    esac
}

# dist/updates/updates_tests.sh sources it for its functions alone.
[[ ${BLUERUNE_UPDATES_SOURCED:-0} == 1 ]] || main "$@"
