#!/bin/bash
# SPDX-License-Identifier: GPL-3.0-only
set -o pipefail
TUI_BINDIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
if [[ -x $TUI_BINDIR/slackresolve ]]; then CLI=$TUI_BINDIR/slackresolve; else CLI=/usr/sbin/slackresolve; fi
DIALOG=${DIALOG:-dialog}
declare -a TUI_OPTIONS=() TUI_SESSION_OPTIONS=()
TUI_REPO=slackpkg; TUI_ROOT=/; TUI_PREFER=; TUI_LAST_PLAN=
while (( $# )); do
    case $1 in
        --root|--cache)
            (( $# >= 2 )) || exit 1; TUI_OPTIONS+=("$1" "$2")
            if [[ $1 == --root ]]; then TUI_ROOT=$2; else TUI_SESSION_OPTIONS+=("$1" "$2"); fi
            shift 2;;
        --repo) (( $# >= 2 )) || exit 1; TUI_REPO=$2; shift 2;;
        --help|-h) printf 'Usage: slackresolve-tui [--root DIR] [--repo DIR|slackpkg] [--cache DIR]\n'; exit;;
        *) printf 'Unknown option: %s\n' "$1" >&2; exit 1;;
    esac
done
command -v "$DIALOG" >/dev/null || { printf 'dialog is required. Install the Slackware dialog package.\n' >&2; exit 1; }
if ! { exec {TUI_TTY}<>/dev/tty; } 2>/dev/null; then
    printf 'An interactive terminal is required.\n' >&2; exit 1
fi
case ${TERM:-} in ''|dumb|unknown) printf 'A usable TERM setting is required.\n' >&2; exit 1;; esac
umask 077
TUI_WORK=$(mktemp -d "${TMPDIR:-/tmp}/slackresolve-tui.XXXXXXXX") || exit 1
trap 'rm -rf -- "$TUI_WORK"' EXIT
tui_dimensions() {
    local rows cols
    read -r rows cols < <(stty size <&"$TUI_TTY" 2>/dev/null)
    [[ $rows =~ ^[0-9]+$ && $rows -ge 18 ]] || rows=24
    [[ $cols =~ ^[0-9]+$ && $cols -ge 60 ]] || cols=80
    TUI_HEIGHT=$((rows-4)); (( TUI_HEIGHT <= 24 )) || TUI_HEIGHT=24
    TUI_WIDTH=$((cols-4)); (( TUI_WIDTH <= 100 )) || TUI_WIDTH=100
}
tui_view() { "$DIALOG" "$@" <&"$TUI_TTY" >&"$TUI_TTY" 2>&"$TUI_TTY"; }
tui_select() {
    local result=$TUI_WORK/selection code
    "$DIALOG" --output-fd 3 "$@" 3>"$result" <&"$TUI_TTY" >&"$TUI_TTY" 2>&"$TUI_TTY"
    code=$?; (( code == 0 )) || return "$code"
    cat -- "$result"
}
tui_file() { tui_dimensions; tui_select --title "$1" --fselect "$2" "$TUI_HEIGHT" "$TUI_WIDTH"; }
tui_plan_name() {
    tui_select --title 'Save dependency plan' --inputbox \
        'Plan filename. Its adjacent .d directory stores the exact packages.' 0 0 \
        "${HOME:-$PWD}/slackresolve-$(date +%Y%m%d-%H%M%S).plan"
}
tui_run() {
    local title=$1; shift
    local log=$TUI_WORK/results progress=$TUI_WORK/progress status=$TUI_WORK/status pid result percent message dialog_status
    : > "$log"; printf '0\tStarting...\n' > "$progress"; rm -f -- "$status"
    ( SLACKRESOLVE_PROGRESS_FILE="$progress" "$CLI" "$@" > "$log" 2>&1; printf '%s\n' "$?" > "$status" ) & pid=$!
    tui_dimensions
    {
        while kill -0 "$pid" 2>/dev/null; do
            IFS=$'\t' read -r percent message < "$progress" || :
            [[ $percent =~ ^[0-9]+$ ]] || percent=0
            printf 'XXX\n%s\n%s\nXXX\n' "$percent" "${message:-Working...}"
            sleep 0.2
        done
        printf '100\n'
    } | "$DIALOG" --input-fd "$TUI_TTY" --title "$title" --gauge 'Working... Press Esc to save the session and stop.' 9 "$TUI_WIDTH" 0 >&"$TUI_TTY" 2>&"$TUI_TTY"
    dialog_status=$?
    if (( dialog_status != 0 )) && kill -0 "$pid" 2>/dev/null; then kill -INT "$pid" 2>/dev/null || :; fi
    wait "$pid" || :; result=1; [[ ! -f $status ]] || read -r result < "$status"
    if [[ $result == 0 ]]; then title="$title - completed"; else title="$title - review required"; fi
    tui_view --title "$title" --textbox "$log" 0 0
    return "$result"
}
tui_resolve_options() {
    RESOLVE_OPTIONS=(--repo "$TUI_REPO" "${TUI_OPTIONS[@]}")
    [[ -z $TUI_PREFER ]] || RESOLVE_OPTIONS+=(--prefer "$TUI_PREFER")
}
while :; do
    choice=$(tui_select --title SlackResolve --menu \
        "Find and install missing Slackware files and ELF dependencies.\nTarget: $TUI_ROOT\nRepository: $TUI_REPO" 0 0 10 \
        program 'Check an installed program' \
        file 'Find the package containing a file' \
        system 'Check the complete system' \
        package 'Install a package with dependencies' \
        resume 'Resume an interrupted resolution' \
        review 'Review a saved plan' \
        apply 'Apply a saved plan' \
        verify 'Verify an applied plan' \
        settings 'Repository and provider preferences' \
        exit 'Exit') || break
    case $choice in
        program)
            program=$(tui_file 'Select an installed program' "${TUI_ROOT%/}/usr/bin/") || continue
            [[ -f $program ]] || { tui_view --msgbox 'Select an existing program.' 0 0; continue; }
            plan=$(tui_plan_name) || continue; [[ -n $plan ]] || continue
            tui_resolve_options; tui_run 'Program dependency check' check-program "$program" --output "$plan" "${RESOLVE_OPTIONS[@]}" || :
            [[ ! -f $plan ]] || TUI_LAST_PLAN=$plan;;
        file)
            filename=$(tui_select --title 'Find a package by file' --inputbox \
                'Exact filename (libabc.so.1) or package path (/usr/bin/example):' 0 0) || continue
            [[ -n $filename ]] || continue
            plan=$(tui_plan_name) || continue; [[ -n $plan ]] || continue
            tui_resolve_options; tui_run 'Generic file search' search-file "$filename" --output "$plan" "${RESOLVE_OPTIONS[@]}" || :
            [[ ! -f $plan ]] || TUI_LAST_PLAN=$plan;;
        system)
            plan=$(tui_plan_name) || continue; [[ -n $plan ]] || continue
            tui_resolve_options; tui_run 'Complete system check' check-system --output "$plan" "${RESOLVE_OPTIONS[@]}" || :
            [[ ! -f $plan ]] || TUI_LAST_PLAN=$plan;;
        package)
            source_choice=$(tui_select --title 'Package source' --menu 'Choose the requested package source.' 0 0 2 \
                official 'Exact package name from the official Slackware repository' local 'Local Slackware package archive') || continue
            if [[ $source_choice == official ]]; then
                package=$(tui_select --title 'Official package' --inputbox 'Exact package base or full name:' 0 0) || continue
            else package=$(tui_file 'Select a Slackware package' "$PWD/") || continue; fi
            [[ -n $package ]] || continue
            plan=$(tui_plan_name) || continue; [[ -n $plan ]] || continue
            tui_resolve_options; tui_run 'Package dependency plan' install "$package" --output "$plan" "${RESOLVE_OPTIONS[@]}" || :
            [[ ! -f $plan ]] || TUI_LAST_PLAN=$plan;;
        resume)
            tui_run 'Saved resolution sessions' sessions "${TUI_SESSION_OPTIONS[@]}" || :
            session=$(tui_select --title 'Resume resolution' --inputbox 'Enter the session identifier shown in the list:' 0 0) || continue
            [[ -n $session ]] || continue
            tui_run 'Resumed dependency resolution' resume "$session" "${TUI_SESSION_OPTIONS[@]}" || :;;
        review|apply|verify)
            plan=$(tui_file 'Select a dependency plan' "${TUI_LAST_PLAN:-$PWD/}") || continue
            [[ -f $plan ]] || { tui_view --msgbox 'Select an existing plan.' 0 0; continue; }
            TUI_LAST_PLAN=$plan
            if [[ $choice == review ]]; then tui_run 'Dependency plan' show "$plan" || :; continue; fi
            if [[ $choice == apply ]]; then
                tui_run 'Dependency plan' show "$plan" || continue
                tui_view --title 'Apply dependency plan' --yesno \
                    'Download verification is complete. Apply every marked install and upgrade operation now?' 0 0 || continue
                if [[ $TUI_ROOT == / && $EUID != 0 ]]; then tui_view --msgbox 'Start SlackResolve from a root shell to apply this plan.' 0 0; continue; fi
            fi
            tui_run "${choice^} dependency plan" "$choice" "$plan" "${TUI_OPTIONS[@]}" || :;;
        settings)
            setting=$(tui_select --title Settings --menu 'Choose a setting.' 0 0 3 \
                slackpkg 'Use official Slackware repositories through slackpkg' \
                local 'Use a local package directory' \
                prefer 'Set preferred provider package names') || continue
            if [[ $setting == slackpkg ]]; then TUI_REPO=slackpkg
            elif [[ $setting == local ]]; then
                tui_dimensions; repo=$(tui_select --title Repository --dselect "$PWD/" "$TUI_HEIGHT" "$TUI_WIDTH") || continue
                [[ ! -d $repo ]] || TUI_REPO=$repo
            else
                preferred=$(tui_select --title 'Provider preferences' --inputbox 'Comma-separated package names:' 0 0 "$TUI_PREFER") || continue
                TUI_PREFER=$preferred
            fi;;
        exit) break;;
    esac
done
tui_view --clear
