#!/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

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)
  --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"
}

# 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:/ { exit !($2 == "f" || $2 == "u") }'
}

# 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
}

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
    run sudo pacman-key --add "$key"
    run sudo pacman-key --lsign-key "$BLUERUNE_FPR"
    ((DRY)) || did "pacman trusts it now"
}

step_repo() {
    step "The [bluerune] repository ($CHANNEL)"
    local new=$TMP/pacman.conf
    conf_with_repo "$PACMAN_CONF" "$CHANNEL" >"$new"
    # 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 it 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 "The [bluerune] section at the end of $PACMAN_CONF becomes:"
        repo_section "$CHANNEL" | sed 's/^/      /'
    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 "added; the file as it was is $PACMAN_CONF.bluerune-backup"
}

step_packages() {
    step "The packages"
    local opts=(--needed)
    ((YES)) && opts+=(--noconfirm)
    note "pacman updates the system (as it always does before installing) and installs what's missing."
    run sudo pacman -Syu "${opts[@]}" bluerune-keyring bluerune-desktop
}

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 SETUP_ARGS=()
    while (($#)); do
        case $1 in
            --edge) CHANNEL=edge ;;
            --stable) CHANNEL=stable ;;
            --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
    # 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
    step_packages
    step_setup
    step "Done"
    note "Updates come with the rest of the system: sudo pacman -Syu"
    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 "$@"
