#!/usr/bin/env bash
# Installs BlueRune and sets it up in the current user's Hyprland session: Hyprland config
# and binds, its own config, power service, other shells, autostart, hypridle. Every change
# it makes is written to a manifest so `--revert` can undo it. It can also save this
# machine's choices as a profile and apply one on another. Run with --help for the options;
# docs/setup.md has the manual steps. The steps are in scripts/install/.
#
# From a checkout, it builds and installs bluerune-git from it. The bluerune package installs
# it as bluerune-setup, with its steps in /usr/share/bluerune/install; then the packages come
# from the BlueRune package repository.
set -euo pipefail

readonly PROG=${0##*/}
ROOT=$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)
readonly ROOT
# Where the package puts BlueRune's shared files: these steps, and the base Hyprland config.
readonly DATA_DIR=${BLUERUNE_DATA_DIR:-/usr/share/bluerune}
if [[ -f $ROOT/scripts/install/common.sh ]]; then
    CHECKOUT=1 PARTS=$ROOT/scripts/install
else
    CHECKOUT=0 PARTS=$DATA_DIR/install
fi
readonly CHECKOUT PARTS
readonly CFG=${XDG_CONFIG_HOME:-$HOME/.config}
readonly HYPR=$CFG/hypr
readonly STATE=${XDG_STATE_HOME:-$HOME/.local/state}/bluerune-install
readonly MANIFEST=$STATE/manifest
# Where the package puts the example config, and where batteries show; tests point these
# at fixtures.
readonly DOC_DIR=${BLUERUNE_DOC_DIR:-/usr/share/doc/bluerune}
readonly POWER_SUPPLY=${BLUERUNE_POWER_SUPPLY:-/sys/class/power_supply}
# Where the login screen finds sessions, and the link to the display manager that starts at boot.
readonly SESSIONS=${BLUERUNE_SESSIONS_DIR:-/usr/share/wayland-sessions}
readonly DM_LINK=${BLUERUNE_DM_LINK:-/etc/systemd/system/display-manager.service}
# Where BlueRune's drop-in points greetd at BlueRune's login screen (dist/greetd).
readonly GREETD_DROP_IN=${BLUERUNE_GREETD_DROP_IN:-/etc/systemd/system/greetd.service.d/bluerune.conf}
readonly MARK='-- bluerune: '
readonly TAIL=' -- bluerune'
readonly SETUP_LINE='require("bluerune-setup") -- bluerune'
readonly BASE_MARK="-- BlueRune's base Hyprland config"
readonly GENERATED='# Generated by BlueRune.'
readonly SHELLS='qs|quickshell|waybar|mako|dunst|swaync|hyprpanel|ags'
readonly TRAY_WATCHERS=' xapp-sn-watcher snixembed xembedsniproxy xembed-sni-proxy '

DRY=0 YES=0 BUILD=1 START=1 REVERT=0 HYPR_OK=0 HAND_SETUP=0 BASE=0 DESKTOP=0
PROFILE='' EXPORT='' PROFILE_POWER=''
OLD_SHELLS=()
declare -A OURS=()

usage() {
    local from='the bluerune-git package, built from this checkout'
    (( CHECKOUT )) || from='its packages from the BlueRune package repository'
    cat <<EOF
Usage: $PROG [options]

Installs BlueRune ($from) and sets it up for
you in Hyprland. Each step says what it will do and asks first; nothing outside the files
it names is touched, and \`$PROG --revert\` undoes it all. Without a Hyprland config it
installs BlueRune's base config, which needs nothing else.

Options:
  --yes                    accept the default answer to every question
  --dry-run                show every change it would make, and make none
  --no-build               don't build or install the packages
  --desktop                also install bluerune-desktop: the BlueRune session's login screen,
                           clipboard history and core apps (Dolphin, Ark, kitty, mpv, Mousepad)
  --no-start               don't start BlueRune now (it starts at your next login)
  --profile <dir>          apply a profile saved with --export-profile while installing
  --export-profile <dir>   save this machine's choices as a profile in <dir>, and nothing else
  --revert                 undo what earlier runs of this script did
  -h, --help               show this help
EOF
}

for part in common hypr steps profile revert; do
    # shellcheck source=/dev/null
    source "$PARTS/$part.sh"
done

main() {
    while (($#)); do
        case $1 in
            --yes | -y) YES=1 ;;
            --dry-run) DRY=1 ;;
            --no-build) BUILD=0 ;;
            --desktop) DESKTOP=1 ;;
            --no-start) START=0 ;;
            --revert) REVERT=1 ;;
            --profile | --export-profile)
                [[ -n ${2:-} ]] || { say "$PROG: $1 needs a directory" >&2; return 2; }
                if [[ $1 == --profile ]]; then PROFILE=$(realpath -- "$2"); else EXPORT=$2; fi
                shift
                ;;
            -h | --help) usage; return 0 ;;
            *) say "$PROG: unknown option $1" >&2; usage >&2; return 2 ;;
        esac
        shift
    done
    if ((EUID == 0)); then say "$PROG: run it as yourself, not root; it asks sudo when it needs to." >&2; return 1; fi
    if [[ -n $EXPORT ]]; then export_profile "$EXPORT"; return; fi
    (( DRY )) && say "${C}Dry run: nothing is changed.$N"
    if (( REVERT )); then revert; return 0; fi
    if [[ -n $PROFILE ]]; then check_profile || return 1; fi

    say "${B}BlueRune setup$N: installs BlueRune and sets it up in your Hyprland config."
    say "Each step explains itself and asks first. Everything it changes can be undone with $PROG --revert."
    [[ -n $PROFILE ]] && say "The choices saved in the profile $PROFILE are the defaults."
    step_backup
    step_build
    step_session
    step_power
    step_config
    step_hypr
    if (( HYPR_OK && ! BASE )); then
        step_shells
    fi
    step_autostart
    step_hypridle
    step_start
    step_import
    heading "Done"
    (( HAND_SETUP )) && say "An older hand setup was found (a require of BlueRune's files); it's commented out, as bluerune-setup.lua loads them now."
    say "Log out and back in if BlueRune isn't running yet. Check it with: bluerunectl ping"
    [[ -f $MANIFEST ]] && say "What was changed is listed in $MANIFEST."
    return 0
}

main "$@"
