#!/usr/bin/env bash
# BlueRune's installer, served at https://bluerune.dev/install:
#
#   curl -fsSL https://bluerune.dev/install | bash
#   curl -fsSL https://bluerune.dev/install | bash -s -- --edge
#
# On Arch Linux (x86_64), run as yourself: it trusts BlueRune's package signing key (once its
# fingerprint matches the one written here), adds the [bluerune] repository to
# /etc/pacman.conf, installs bluerune-keyring and bluerune-desktop with pacman, and runs
# bluerune-setup to set BlueRune up for you. Running it again does only what isn't done.
# Everything happens in main, called on the last line, so a cut-off download runs nothing.
set -euo pipefail

readonly BLUERUNE_FPR=2D29F036E5A935DA3579C4B5DF4D64C7548CC0EF
readonly PKGS_URL=https://pkgs.bluerune.dev
readonly PACMAN_CONF=/etc/pacman.conf
readonly PACMAN_GNUPG=/etc/pacman.d/gnupg
# Where Arch's servers come from on a BlueRune system (bluerune-mirrorlist), and what says
# whether they are held at BlueRune's tested date.
readonly ARCH_LIST=${BLUERUNE_ARCH_LIST:-/etc/pacman.d/bluerune-arch}
readonly UPDATES_CONF=${BLUERUNE_UPDATES_CONF:-/etc/bluerune/updates.conf}
# Where desktop sessions are listed: a system with one has a desktop of its own already.
readonly SESSION_DIRS=${BLUERUNE_SESSION_DIRS:-/usr/share/wayland-sessions /usr/share/xsessions}
# The display manager that starts at boot.
readonly DM_LINK=${BLUERUNE_DM_LINK:-/etc/systemd/system/display-manager.service}

if [[ -t 1 ]]; then B=$'\e[1m' G=$'\e[32m' C=$'\e[36m' R=$'\e[31m' N=$'\e[0m'; else B='' G='' C='' R='' N=''; fi
step() { printf '\n%s==> %s%s\n' "$B" "$*" "$N"; }
note() { printf '    %s\n' "$*"; }
did() { printf '    %sdone:%s %s\n' "$G" "$N" "$*"; }
would() { printf '    %s[dry run] would%s %s\n' "$C" "$N" "$*"; }
die() { printf '%sbluerune install: %s%s\n' "$R" "$*" "$N" >&2; exit 1; }

usage() {
    cat <<EOF
Usage: curl -fsSL https://bluerune.dev/install | bash -s -- [options] [-- bluerune-setup options]

Installs BlueRune on Arch Linux from its package repository, then sets it up for you.
  --edge       the edge channel: every release as soon as it's out
  --stable     the stable channel (the default)
  --hold       hold all of Arch at the date BlueRune was last tested with, moved forward
               once BlueRune passes its tests on a newer one (the default on a new system)
  --live       follow Arch's updates as they come, untested with BlueRune (the default on
               a system that has a desktop already)
  --yes        don't ask: pacman and bluerune-setup take their default answers
  --dry-run    show what it would do, change nothing
  --no-setup   install the packages only; run bluerune-setup yourself later
  -h, --help   show this help
EOF
}

# The [bluerune] section for a channel.
repo_section() {
    printf '%s\n' '[bluerune]' \
        "# BlueRune (https://bluerune.dev), signed by $BLUERUNE_FPR; added by its installer." \
        'SigLevel = Required' \
        "Server = $PKGS_URL/$1/\$arch"
}

# conf_with_repo <pacman.conf> <channel>: the file with its [bluerune] section, if any, taken
# out and the channel's added at the end. After Arch's own repositories, so a package of the
# same name always comes from Arch's; BlueRune's packages have names of their own.
conf_with_repo() {
    SECTION=$(repo_section "$2") awk '
        /^[[:space:]]*\[[^]]+\][[:space:]]*$/ { skip = ($0 ~ /^[[:space:]]*\[bluerune\][[:space:]]*$/) }
        !skip { lines[++n] = $0 }
        END {
            while (n > 0 && lines[n] ~ /^[[:space:]]*$/) n--
            for (i = 1; i <= n; i++) print lines[i]
            print ""
            print ENVIRON["SECTION"]
        }' "$1"
}

# conf_with_arch_list <pacman.conf>: the file with Arch's [core], [extra] and [multilib]
# (commented out or not) taking their servers from $ARCH_LIST, which bluerune-updates
# writes: the tested date's snapshot, or the system's own mirror list. A Server line of
# their own is commented out, so nothing comes from elsewhere. Applying it again changes
# nothing.
conf_with_arch_list() {
    awk -v list="$ARCH_LIST" '
        /^[[:space:]]*#?[[:space:]]*\[[^]]+\][[:space:]]*$/ {
            name = $0
            gsub(/[#[:space:]]|\[|\]/, "", name)
            ours = (name == "core" || name == "extra" || name == "multilib")
        }
        ours && /^[[:space:]]*#?[[:space:]]*Include[[:space:]]*=/ {
            print (($0 ~ /^[[:space:]]*#/) ? "#" : "") "Include = " list
            next
        }
        ours && /^[[:space:]]*Server[[:space:]]*=/ { print "#" $0 "   # BlueRune: the servers are in " list; next }
        { print }' "$1"
}

# has_desktop: a desktop session other than BlueRune's is installed.
has_desktop() {
    local dir file
    for dir in $SESSION_DIRS; do
        for file in "$dir"/*.desktop; do
            [[ -e $file && ${file##*/} != bluerune*.desktop ]] && return 0
        done
    done
    return 1
}

# default_hold: 1 to hold Arch at the tested date, 0 to follow it directly: as chosen
# before; else held on a new system, and live on one with a desktop already, whose
# packages would otherwise go back to the tested date's.
default_hold() {
    local value
    if [[ -r $UPDATES_CONF ]]; then
        value=$(awk -F= '/^[[:space:]]*hold[[:space:]]*=/ { v = $2; gsub(/[[:space:]]/, "", v) } END { print tolower(v) }' "$UPDATES_CONF")
        case $value in false | no | off) echo 0 ;; *) echo 1 ;; esac
        return 0
    fi
    if has_desktop; then echo 0; else echo 1; fi
}

# key_fingerprints <key file>: the fingerprint of each primary key in it, read without
# importing it anywhere.
key_fingerprints() {
    local home status=0
    home=$(mktemp -d)
    GNUPGHOME=$home gpg --batch --quiet --with-colons --import-options show-only --import "$1" 2>/dev/null |
        awk -F: '/^pub:/ { want = 1; next } /^fpr:/ && want { print $10; want = 0 } /^sub:/ { want = 0 }' || status=$?
    rm -rf "$home"
    return "$status"
}

# check_key <key file>: it holds BlueRune's key and nothing else.
check_key() {
    local found
    found=$(key_fingerprints "$1")
    [[ $found == "$BLUERUNE_FPR" ]]
}

# key_trusted: pacman's keyring has the key, signed by its local key (full validity).
key_trusted() {
    sudo gpg --homedir "$PACMAN_GNUPG" --no-permission-warning --batch --with-colons --list-keys "$BLUERUNE_FPR" 2>/dev/null |
        awk -F: '/^pub:/ && !seen { seen = 1; ok = ($2 == "f" || $2 == "u") } END { exit !ok }'
}

# has_own_key: pacman's keyring has a secret key, to sign the keys it trusts with.
has_own_key() {
    sudo gpg --homedir "$PACMAN_GNUPG" --no-permission-warning --batch --with-colons --list-secret-keys 2>/dev/null |
        awk -F: '/^sec:/ { found = 1 } END { exit !found }'
}

# run <command...>: runs it, or says it would.
run() {
    if ((DRY)); then would "run: $*"; return 0; fi
    note "\$ $*"
    "$@"
}

check_system() {
    [[ -f /etc/arch-release ]] && command -v pacman >/dev/null || die "BlueRune installs on Arch Linux; this isn't it."
    [[ $(uname -m) == x86_64 ]] || die "BlueRune's packages are for x86_64; this is $(uname -m)."
    ((EUID != 0)) || die "run it as yourself, not root; it asks sudo when it needs to."
    command -v sudo >/dev/null || die "it needs sudo, to change pacman's configuration and install packages."
    local tool
    for tool in curl gpg awk; do command -v "$tool" >/dev/null || die "it needs $tool."; done
}

# check_channel: the channel has a database. A repository pacman can't sync would stop every
# update, so nothing is changed for one that isn't there.
check_channel() {
    local db=$PKGS_URL/$CHANNEL/$(uname -m)/bluerune.db
    curl -fsS -o /dev/null --head "$db" 2>/dev/null ||
        die "the $CHANNEL channel has no packages yet ($db); nothing was changed. Try --edge."
}

step_key() {
    step "BlueRune's signing key"
    local key=$TMP/bluerune.asc
    curl -fsSL "$PKGS_URL/bluerune.asc" -o "$key" || die "couldn't download $PKGS_URL/bluerune.asc"
    check_key "$key" || die "$PKGS_URL/bluerune.asc isn't the key $BLUERUNE_FPR; stopping."
    note "Downloaded, and its fingerprint is $BLUERUNE_FPR."
    if ((!DRY)) && key_trusted; then note "pacman trusts it already."; return 0; fi
    # pacman trusts a key by signing it with a key of its own, which pacman-key --init makes;
    # an install always has one, a container image may not.
    if ((!DRY)) && ! has_own_key; then
        note "pacman's keyring has no key of its own to sign others with yet; making one."
        run sudo pacman-key --init
    fi
    run sudo pacman-key --add "$key"
    run sudo pacman-key --lsign-key "$BLUERUNE_FPR"
    ((DRY)) || did "pacman trusts it now"
}

# replace_conf <new file> <what it adds>: pacman.conf replaced by the new file, shown as a
# difference first; the file as it was before BlueRune's installer first changed it is kept
# as pacman.conf.bluerune-backup.
replace_conf() {
    local new=$1 what=$2
    # Arch's base has no diffutils, so no cmp: the files are the same if their sums are.
    if [[ $(sha256sum <"$PACMAN_CONF") == "$(sha256sum <"$new")" ]]; then note "$PACMAN_CONF has $what already."; return 0; fi
    if command -v diff >/dev/null; then
        diff -u --label "$PACMAN_CONF" --label "$PACMAN_CONF (new)" "$PACMAN_CONF" "$new" | sed 's/^/    /' || true
    else
        note "$PACMAN_CONF gets $what."
    fi
    if ((DRY)); then would "write that to $PACMAN_CONF"; return 0; fi
    [[ -e $PACMAN_CONF.bluerune-backup ]] || run sudo cp -p "$PACMAN_CONF" "$PACMAN_CONF.bluerune-backup"
    run sudo install -m644 "$new" "$PACMAN_CONF"
    did "$what; the file as it was is $PACMAN_CONF.bluerune-backup"
}

step_repo() {
    step "The [bluerune] repository ($CHANNEL)"
    conf_with_repo "$PACMAN_CONF" "$CHANNEL" >"$TMP/pacman.conf"
    replace_conf "$TMP/pacman.conf" "the [bluerune] section at its end"
}

# choose_hold: HOLD set from --hold or --live, else asked, with default_hold's answer as the
# default (taken without asking with --yes or --dry-run).
choose_hold() {
    [[ -n $HOLD ]] && return 0
    local default answer
    default=$(default_hold)
    step "Arch Linux's updates"
    note "Hold: all of Arch stays at the date BlueRune was last tested with, and moves forward"
    note "      once BlueRune passes its tests on a newer one (days, usually). Nothing breaks"
    note "      because Hyprland or a library changed before BlueRune did."
    note "Live: Arch's updates as they come, as on any Arch system; Hyprland can get ahead of"
    note "      BlueRune for a while. Pacman warns when it does."
    if has_desktop && [[ ! -r $UPDATES_CONF ]]; then
        note "This system has a desktop already, so live is the default: holding would take its"
        note "packages back to the tested date's."
    fi
    if ((YES || DRY)); then
        HOLD=$default
        note "Taking the default: $( ((HOLD)) && echo hold || echo live)."
        return 0
    fi
    local prompt='[Y/n]'
    ((default)) || prompt='[y/N]'
    read -r -p "    Hold Arch at BlueRune's tested date? $prompt " answer || answer=''
    case ${answer,,} in
        y | yes) HOLD=1 ;;
        n | no) HOLD=0 ;;
        *) HOLD=$default ;;
    esac
}

# step_updates: updates.conf and the mirror list as chosen (bluerune-updates, which
# bluerune-mirrorlist brings), then pacman.conf's Arch repositories taking their servers
# from that list.
step_updates() {
    local how=on
    ((HOLD)) || how=off
    step "Arch Linux's updates: $( ((HOLD)) && echo "held at BlueRune's tested date" || echo "followed directly")"
    run sudo bluerune-updates hold "$how" --channel "$CHANNEL"
    conf_with_arch_list "$PACMAN_CONF" >"$TMP/pacman.conf.arch"
    replace_conf "$TMP/pacman.conf.arch" "[core], [extra] and [multilib] reading their servers from $ARCH_LIST"
}

# keep_sddm: SDDM, when it is the login screen and pacman holds it as only a dependency (of
# bluerune-desktop before 3, which no longer depends on it), marked as installed on purpose,
# so it doesn't become an orphan that `pacman -Rns $(pacman -Qdtq)` would remove. Which login
# screen starts is left as it is.
keep_sddm() {
    [[ $(readlink -- "$DM_LINK" 2>/dev/null) == */sddm.service ]] || return 0
    pacman -Qdq sddm >/dev/null 2>&1 || return 0
    note "Your login screen is SDDM, which bluerune-desktop no longer brings; keeping it installed."
    run sudo pacman -D --asexplicit sddm
}

step_packages() {
    step "The packages"
    local opts=(--needed) sync=-Syu
    ((YES)) && opts+=(--noconfirm)
    note "pacman updates the system (as it always does before installing), then installs"
    note "BlueRune's key and bluerune-mirrorlist, which says which Arch updates come."
    run sudo pacman -Syu "${opts[@]}" bluerune-keyring bluerune-mirrorlist
    step_updates
    step "BlueRune's desktop"
    if ((HOLD)); then
        # -uu: what is newer than the tested date goes back to the date's version.
        sync=-Syuu
        note "With Arch held, anything newer than the tested date goes back to it (pacman -Syuu)."
    fi
    run sudo pacman "$sync" "${opts[@]}" bluerune-desktop
    keep_sddm
}

step_setup() {
    step "Setting BlueRune up for you"
    if ((NO_SETUP)); then note "Skipped (--no-setup). Run bluerune-setup when you like."; return 0; fi
    local opts=()
    ((YES)) && opts+=(--yes)
    ((DRY)) && opts+=(--dry-run)
    if ! command -v bluerune-setup >/dev/null; then
        ((DRY)) && { would "run: bluerune-setup ${opts[*]} ${SETUP_ARGS[*]}"; return 0; }
        die "bluerune-setup isn't installed; did pacman install bluerune?"
    fi
    note "\$ bluerune-setup ${opts[*]} ${SETUP_ARGS[*]}"
    bluerune-setup "${opts[@]}" "${SETUP_ARGS[@]}"
}

main() {
    CHANNEL=stable YES=0 DRY=0 NO_SETUP=0 HOLD='' SETUP_ARGS=()
    while (($#)); do
        case $1 in
            --edge) CHANNEL=edge ;;
            --stable) CHANNEL=stable ;;
            --hold) HOLD=1 ;;
            --live) HOLD=0 ;;
            --yes | -y) YES=1 ;;
            --dry-run) DRY=1 ;;
            --no-setup) NO_SETUP=1 ;;
            -h | --help) usage; return 0 ;;
            --) shift; SETUP_ARGS=("$@"); break ;;
            *) usage >&2; die "unknown option $1" ;;
        esac
        shift
    done
    check_system
    check_channel
    # Piped into bash, the script is stdin: questions are asked on the terminal instead.
    if [[ ! -t 0 ]]; then
        if { : </dev/tty; } 2>/dev/null; then exec </dev/tty
        elif ((!YES && !DRY)); then die "there's no terminal to ask questions on; run it with --yes."; fi
    fi
    TMP=$(mktemp -d)
    trap 'rm -rf "$TMP"' EXIT
    printf '%sBlueRune%s: installs it from %s (%s channel).\n' "$B" "$N" "$PKGS_URL" "$CHANNEL"
    ((DRY)) && printf '%sDry run: nothing is changed.%s\n' "$C" "$N"
    step_key
    step_repo
    choose_hold
    step_packages
    step_setup
    step "Done"
    note "Updates come with the rest of the system: sudo pacman -Syu"
    if ((HOLD)); then
        note "Arch is held at BlueRune's tested date; to follow it directly: sudo bluerune-updates hold off"
    else
        note "Arch is followed directly; to hold it at BlueRune's tested date: sudo bluerune-updates hold on"
    fi
    note "At the login screen, pick the \"BlueRune\" session."
}

# release/install_tests.sh sources it for its functions alone.
[[ ${BLUERUNE_INSTALL_SOURCED:-0} == 1 ]] || main "$@"
