#!/bin/bash

# =======================
# Define Colors
RED='\e[41m'
NC='\e[0m' # No color
BG='\e[7m' # Highlighting Background color
TC='\e[1m' # Highlighting Text color

# =======================
# Service messages section
# Wrong Option
ERRORMSG="$RED Wrong option $NC"
TRYAGAINMSG=" Please try again..."

# =======================
# Pacman installation
INSTALLPKGS="sudo pacman -Syu"

# =======================
# Backend selection: mhwd on Manjaro, archhw without it
HAS_MHWD=0
# BMENU_FORCE_ARCH=1 forces the Arch branch
if [ -x "$(command -v mhwd)" ] && [ "${BMENU_FORCE_ARCH:-0}" != "1" ]; then
    HAS_MHWD=1
fi

# =======================
# Arch kernel lists, answered by archhw
function arch_available_kernels() {
    archhw available-kernels 2>/dev/null
}

function arch_installed_kernels() {
    archhw installed-kernels 2>/dev/null
}

# The running kernel is never offered for removal
function arch_running_kernel() {
    archhw running-flavour 2>/dev/null
}

# =======================
# Input handling
# Drop an ENTER left in the input buffer by a menu key
function drain_enter() {
    local _rest
    read -r -n 1 -t 0.2 _rest || true
}

function confirm_line() { # <question> -> rc 0 only on an explicit yes
    local a empty=0
    echo -e " $BG $1 [y|N] ${NC}"
    while true; do
        if ! read -r a; then
            [ -n "$a" ] || { echo -e " ${TC}No input, nothing was installed.${NC}"; return 1; }
        fi
        if [ -z "$a" ]; then
            if [ -t 0 ]; then
                continue
            fi
            empty=$((empty + 1))
            [ "$empty" -lt 3 ] || return 1
            continue
        fi
        case "$a" in
        y | Y | yes | YES)
            return 0
            ;;
        *)
            echo -e " ${TC}Cancelled.${NC}"
            return 1
            ;;
        esac
    done
}

# =======================
# mhwd-ui functions
cd || exit
# Temp dir for the kernel lists, removed on exit
KERNELDIR=$(mktemp -d -t toolbox-mhwd.XXXXXX)
function cleanup_kernelfiles() {
    rm -rf "$KERNELDIR" 2>/dev/null
}
trap cleanup_kernelfiles EXIT
in_array() {
    local -n haystack=$1
    local needle=$2
    local i
    for i in "${haystack[@]}"; do
        if [[ "$i" == "$needle" ]]; then
            return 0
        fi
    done
    return 1
}

function install_kernel() {
    PS3="which kernel do you wish to install? (press ctrl+d to proceed, ctrl+c to cancel): "
    picks=()
    # One array element per kernel name
    kernels=()
    if [ "$HAS_MHWD" == "1" ]; then
        while IFS= read -r k; do
            [ -n "$k" ] && kernels+=("$k")
        # -x: whole line match, so linux does not drop linux-lts
        done < <(grep -vxF -f "$KERNELDIR/installed_kernels" "$KERNELDIR/available_kernels")
    else
        while IFS= read -r k; do
            [ -n "$k" ] && kernels+=("$k")
        done < <(arch_available_kernels | grep -vxF -f <(arch_installed_kernels))
    fi
    kernels+=("proceed" "cancel")

    select pick in "${kernels[@]}"; do
        case $pick in
        proceed)
            break
            ;;
        cancel)
            exit
            ;;
        "")
            continue
            ;;
        *)
            if in_array picks "$pick"; then
                mapfile -t picks < <(printf -- '%s\n' "${picks[@]}" | grep -vxF -- "$pick")
            else
                picks+=("$pick")
            fi
            printf 'Selected: %s\n' "${picks[*]}"
            ;;
        esac
    done

    if [ "${#picks[@]}" -gt 0 ]; then
        printf 'Installing %s\n' "${picks[*]}"
        if [ "$HAS_MHWD" == "1" ]; then
            sudo mhwd-kernel -i "${picks[@]}"
        else
            archhw install-kernel "${picks[@]}"
        fi
    fi
}

function remove_kernel() {
    PS3="which kernel do you wish to remove? (press ctrl+d to proceed, ctrl+c to cancel): "
    picks=()
    # One array element per kernel name
    kernels=()
    if [ "$HAS_MHWD" == "1" ]; then
        while IFS= read -r k; do
            [ -n "$k" ] && kernels+=("$k")
        # -x: whole line match, the running kernel drops only its own line
        done < <(grep -vxF -f "$KERNELDIR/running_kernel" "$KERNELDIR/installed_kernels")
    else
        running=$(arch_running_kernel)
        while IFS= read -r k; do
            [ -n "$k" ] && kernels+=("$k")
        done < <(arch_installed_kernels | grep -vxF -- "${running:-impossible-name}")
    fi
    kernels+=("proceed" "cancel")

    select pick in "${kernels[@]}"; do
        case $pick in
        proceed)
            break
            ;;
        cancel)
            exit
            ;;
        "")
            continue
            ;;
        *)
            if in_array picks "$pick"; then
                mapfile -t picks < <(printf -- '%s\n' "${picks[@]}" | grep -vxF -- "$pick")
            else
                picks+=("$pick")
            fi
            printf 'Selected: %s\n' "${picks[*]}"
            ;;
        esac
    done

    if [ "${#picks[@]}" -gt 0 ]; then
        printf 'Removing %s\n' "${picks[*]}"
        if [ "$HAS_MHWD" == "1" ]; then
            sudo mhwd-kernel -r "${picks[@]}"
        else
            archhw remove-kernel "${picks[@]}"
        fi
    fi
}

if [ "$HAS_MHWD" == "1" ]; then
    mhwd-kernel -li | awk 'NR==1 {print $4}' | tr -d '()' >"$KERNELDIR/running_kernel"
    mhwd-kernel -li | awk 'NR > 2 { print $2}' >"$KERNELDIR/installed_kernels"
    mhwd-kernel -l | awk 'NR > 1 { print $2}' >"$KERNELDIR/available_kernels"
fi

# Run infinite loop for UI / menu, till the user quits using the "quit" option or CTRL+C.
while true; do

    # Define Menu entries which will be run with the echo command
    E0="\e[1mQ\e[0muit"
    E1="\e[1mI\e[0mnstall a Kernel"
    E2="\e[1mR\e[0memove a Kernel"
    E3="Use \e[1mF\e[0mree Graphics"
    E4="Use \e[1mN\e[0monfree Graphics"
    E5="\e[1mL\e[0mist Installed Drivers"
    E6="\e[1mC\e[0monfigure Touchpad"
    E7="\e[1mS\e[0mystem Temperatures"
    E8="\e[1mD\e[0misk Usage"
    E9="\e[1mH\e[0mome Folder Usage"
    E10="\e[1mB\e[0mios Information"
    E11="P\e[1mo\e[0mwer Consumption"
    E12="\e[1mP\e[0mrinters"

    printf '\33[H\33[2J' # Use this instead of the clear command

    echo
    echo -e "                       $BG$TC Hardware and Drivers $NC"
    echo -e " $TC+----------------------------------------------------------------+$NC"
    echo -e " $TC|$NC    $BG 1 $NC $E1        $TC|$NC    $BG 2 $NC $E2        $TC|$NC"
    echo -e " $TC|$NC--------------------------------$TC|$NC-------------------------------$TC|$NC"
    echo -e " $TC|$NC    $BG 3 $NC $E3       $TC|$NC    $BG 4 $NC $E4   $TC|$NC"
    echo -e " $TC|$NC--------------------------------$TC|$NC-------------------------------$TC|$NC"
    echo -e " $TC|$NC    $BG 5 $NC $E5  $TC|$NC    $BG 6 $NC $E6     $TC|$NC"
    echo -e " $TC|$NC--------------------------------$TC|$NC-------------------------------$TC|$NC"
    echo -e " $TC|$NC    $BG 7 $NC $E7 $NC    $TC|$NC    $BG 8 $NC $E8             $TC|$NC"
    echo -e " $TC|$NC--------------------------------$TC|$NC-------------------------------$TC|$NC"
    echo -e " $TC|$NC    $BG 9 $NC $E9       $TC|$NC    $BG B $NC $E10       $TC|$NC"
    echo -e " $TC|$NC--------------------------------$TC|$NC-------------------------------$TC|$NC"
    echo -e " $TC|$NC    $BG O $NC $E11       $TC|$NC    $BG P $NC $E12               $TC|$NC"
    echo -e " $TC+----------------------------------------------------------------+$NC"
    echo ""
    echo -e "  Enter marked number or letter   -    $BG 0 $NC $E0 "

    # save entered number/letter in variable "choice"
    read -r -n 1 -e choice || exit 0
    [ -n "$choice" ] && drain_enter
    if [ -z "$choice" ]; then
        # An empty answer is ENTER: redraw the menu
        if [ -t 0 ]; then
            continue
        fi
        EMPTY_RUNS=$((${EMPTY_RUNS:-0} + 1))
        [ "$EMPTY_RUNS" -lt 3 ] || exit 0
        continue
    fi
    EMPTY_RUNS=0

    # test, whether "choice" fits any of the following numbers or letters
    case "$choice" in
    1 | I | i)
        printf '\33[H\33[2J'
        install_kernel
        echo ""
        ;;
    2 | R | r)
        printf '\33[H\33[2J'
        remove_kernel
        echo ""
        ;;
    3 | F | f)
        printf '\33[H\33[2J'
        if [ "$HAS_MHWD" == "1" ]; then
            sudo mhwd -a pci free 0300
        else
            # archhw runs with --yes only after this question
            if confirm_line "Install the open source driver stack with archhw"; then
                archhw install-open --yes
            fi
        fi
        echo
        echo -e " $RED To return to Hardware and Drivers press ENTER $NC"
        # wait for input, e.g. by pressing ENTER:
        read -r
        ;;
    4 | N | n)
        printf '\33[H\33[2J'
        if [ "$HAS_MHWD" == "1" ]; then
            sudo mhwd -a pci nonfree 0300
        else
            if confirm_line "Install the proprietary NVIDIA driver with archhw"; then
                archhw install-proprietary --yes
            fi
        fi
        echo
        echo -e " $RED To return to Hardware and Drivers press ENTER $NC"
        # wait for input, e.g. by pressing ENTER:
        read -r
        ;;
    5 | L | l)
        printf '\33[H\33[2J'
        if [ "$HAS_MHWD" == "1" ]; then
            mhwd -li -d
        else
            archhw list
        fi
        echo
        echo -e " $RED To return to Hardware and Drivers press ENTER $NC"
        # wait for input, e.g. by pressing ENTER:
        read -r
        ;;
    6 | C | c)
        printf '\33[H\33[2J'
        xinput_tui
        ;;
    7 | S | s)
        printf '\33[H\33[2J'
        sensors
        echo
        echo -e " $RED To return to Hardware and Drivers press ENTER $NC"
        # wait for input, e.g. by pressing ENTER:
        read -r
        ;;
    8 | D | d)
        printf '\33[H\33[2J'
        ncdu -x /
        echo
        echo -e " $RED To return to Hardware and Drivers press ENTER $NC"
        # wait for input, e.g. by pressing ENTER:
        read -r
        ;;
    9 | H | h)
        printf '\33[H\33[2J'
        ncdu -x "$HOME"
        echo
        echo -e " $RED To return to Hardware and Drivers press ENTER $NC"
        # wait for input, e.g. by pressing ENTER:
        read -r
        ;;
    B | b)
        printf '\33[H\33[2J'
        sudo dmidecode -t bios
        echo
        echo -e " $RED To return to Hardware and Drivers press ENTER $NC"
        # wait for input, e.g. by pressing ENTER:
        read -r
        ;;
    O | o)
        printf '\33[H\33[2J'
        if [[ -f /usr/bin/powertop ]]; then
            sudo powertop
        else
            echo "Installing Powertop"
            if [[ -f /var/lib/pacman/db.lck ]]; then
                echo "powertop is not installed and Pacman seems to be in use"
            else
                $INSTALLPKGS powertop && sudo powertop
            fi
        fi
        echo
        echo -e " $RED To return to Hardware and Drivers press ENTER $NC"
        # wait for input, e.g. by pressing ENTER:
        read -r
        ;;
    P | p)
        printf '\33[H\33[2J'
        bcups
        ;;
    0 | Q | q)
        printf '\33[H\33[2J' && exit
        ;;
    *) # do this, if $choice variable contains anything else not offered above
        echo -e "$ERRORMSG"
        echo -e "$TRYAGAINMSG"
        sleep 2
        ;;
    esac
done
