#!/bin/bash

# =======================
# Local vars
DISABLEPACUI=0
DISABLEMHWD=0

# =======================
# 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..."
# File Manager (Ranger)
INSTALLINGRNG1MSG="Installing ranger to manage files"
CLIFMNOTINSTMSG="No cli filemanager is installed and Pacman seems to be in use"
# Task Manager (btop)
INSTALLINGTASKMANMSG="Installing btop to manage tasks"
TASKMANNOTINSTMSG="Btop is not installed and Pacman seems to be in use"
# File Search (Rifle)
RIFLENOTINSTMSG="Rifle is not installed and Pacman seems to be in use"
# Web Browser (Links)
INSTALLINGCLIBRWOSMSG="Installing links to surf the web"
CLIBROWSNOTINSTMSG="No cli browser installed and Pacman seems to be in use"
# PacUI
INSTALLINGPACUIMSG="Installing PacUI for package management"
PACUINOTINSTMSG="PacUI is not installed and Pacman seems to be in use"
PACUIFAILEDINSTMSG="Failed to install PacUI"
# inxi
INSTALLINGINXIMSG="Installing inxi to display system information"
INXINOTINSTMSG="inxi is not installed and Pacman seems to be in use"
# cpupower
INSTALLINGCPUPOWERMSG="Installing cpupower to display frequency-info"
CPUPOWERNOTINSTMSG="cpupower is not installed and Pacman seems to be in use"
# cmus
INSTALLINGCMUSMSG="Installing cmus to play music"
CMUSNOTINSTMSG="cmus is not installed and Pacman seems to be in use"

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

# =======================
# Main Menu functions
# PacUI
function package_manager_ui() {
    if [ -x "$(command -v pacui)" ]; then # If command exists
        pacui                             # Run it
    else
        echo "$INSTALLINGPACUIMSG"             # Install Message
        if [ -e /var/lib/pacman/db.lck ]; then # If file exists
            echo "$PACUINOTINSTMSG"            # Not installed Message
        else
            if $INSTALLPKGS pacui && pacui; then # Else install package and run it
                DISABLEPACUI=0
                echo "installed" &>/dev/null
            else
                echo -e " \e[41m Installation failed, do you want to download PacUI from source? [Y|n] \e[0m"
                read -r -n 1 -e answer # save user input in "answer" variable (only accept 1 character as input)

                case ${answer:-n} in # if ENTER is pressed, the variable "answer" is empty. if "answer" is empty, its default value is "no".
                y | Y)               # do this, if "answer" is y or Y.

                    PACUISOURCE=https://raw.githubusercontent.com/excalibur1234/pacui/master/pacui
                    PACUITMPDIR=/tmp/toolbox
                    PACUIDOWNLOAD=$(mkdir -p "$PACUITMPDIR" && wget -O "$PACUITMPDIR/pacui" "$PACUISOURCE" && chmod +x "$PACUITMPDIR/pacui")

                    if $PACUIDOWNLOAD && sh "$PACUITMPDIR/pacui"; then
                        DISABLEPACUI=3
                        PACUIFROMSOURCE=1
                    fi
                    ;;
                *) # do this in all other cases
                    DISABLEPACUI=2
                    PACUIFAILEDINSTALL=1
                    echo "$PACUIFAILEDINSTMSG"
                    ;;
                esac # end of "case" loop
            fi
        fi
    fi
}

# File Manager
function cli_filemanager() {
    if [ -x "$(command -v ranger)" ]; then
        echo -e " $RED Press $BG Q $NC$RED to return to ToolBox $NC"
        sleep 2
        ranger
    elif [ -x "$(command -v mc)" ]; then
        mc
    else
        echo "$INSTALLINGRNG1MSG"
        if [ -e /var/lib/pacman/db.lck ]; then
            echo "$CLIFMNOTINSTMSG"
        else
            $INSTALLPKGS ranger && ranger
        fi
    fi
}

# Web Browser
function cli_browser() {
    if [ -x "$(command -v links)" ]; then
        links
    elif [ -x "$(command -v elinks)" ]; then
        elinks
    elif [ -x "$(command -v w3m)" ]; then
        w3m
    elif [ -x "$(command -v lynx)" ]; then
        lynx
    else
        echo "$INSTALLINGCLIBRWOSMSG"
        if [ -e /var/lib/pacman/db.lck ]; then
            echo "$CLIBROWSNOTINSTMSG"
        else
            $INSTALLPKGS links && links
        fi
    fi
}

# File Search
function file_finder() {
    if [ -x "$(command -v rifle)" ]; then
        rifle "$(find -type f | fzf -e --reverse --prompt="Enter string > " --header="ESC to quit. ")"
    else
        echo "$INSTALLINGRNG1MSG"
        if [ -e /var/lib/pacman/db.lck ]; then
            echo "$RIFLENOTINSTMSG"
        else
            $INSTALLPKGS ranger && rifle "$(find -type f | fzf -e --reverse --prompt="Enter string > " --header="ESC to quit. ")"
        fi
    fi
}

# Taskmanager
function taskmanager() {
    if [ -x "$(command -v btop)" ]; then
        btop
    else
        echo "$INSTALLINGTASKMANMSG"
        if [ -e /var/lib/pacman/db.lck ]; then
            echo "$TASKMANNOTINSTMSG"
        else
            $INSTALLPKGS btop && btop
        fi
    fi
}

# System Information
function sysinfo() {
    if [ -x "$(command -v inxi)" ]; then
        cd "$HOME" || exit
        sudo inxi -v8 | tee "$HOME/.inxi.txt" &>/dev/null
        printf '\33[H\33[2J'
        fzf <"$HOME/.inxi.txt" -i --multi --reverse --info=inline --prompt="Enter string > " --header="TAB key to (un)select. ENTER to view selection. ESC to quit. " --no-unicode
        rm -rf "$HOME/.inxi.txt"
    else
        echo "$INSTALLINGINXIMSG"
        if [ -e /var/lib/pacman/db.lck ]; then
            echo "$INXINOTINSTMSG"
        else
            $INSTALLPKGS inxi && inxi -v8 | fzf -i --multi --reverse --info=inline --prompt="Enter string > " --header="TAB key to (un)select. ENTER to view selection. ESC to quit. " --no-unicode
        fi
    fi
}

# Cpupower frequency-info
function freqinfo() {
    if [ -x "$(command -v cpupower)" ]; then
        sudo cpupower frequency-info
        echo
        echo -e " $RED Displaying frequency-info. To return to ToolBox press ENTER $NC"
        read -r
    else
        echo "$INSTALLINGCPUPOWERMSG"
        if [ -e /var/lib/pacman/db.lck ]; then
            echo "$CPUPOWERNOTINSTMSG"
        else
            $INSTALLPKGS cpupower && sudo cpupower frequency-info
            echo
            echo -e " $RED Displaying frequency-info. To return to ToolBox press ENTER $NC"
            read -r
        fi
    fi
}

# Music Player
function music() {
    cd "$HOME" || exit
    if [ -x "$(command -v cmus)" ]; then
        echo -e " $RED Press $BG 1-7 $NC$RED to navigate and $BG Q $NC$RED to return to ToolBox $NC"
        sleep 3
        cmus
    else
        echo "$INSTALLINGCMUSMSG"
        if [ -e /var/lib/pacman/db.lck ]; then
            echo "$CMUSNOTINSTMSG"
        else
            $INSTALLPKGS cmus && cmus
        fi
    fi
}

# Check if a website is up via "ping"
function isitup() {
    echo -e "Please type in the URL and press ENTER"
    echo -e "For example: \e[7mforum.manjaro.org\e[0m"
    read -p 'URL: ' uservar
    echo ""
    if ping -c1 -W1 "$uservar" &>/dev/null; then
        echo -e " Yay\e[1m $uservar \e[0mis up!"
    else
        echo -e " Oh no\e[1m $uservar \e[0mseems to be down!"
    fi
    echo ""
}

# Random Funny Message
function randArrayElement() {
    arr=(" $RED Nice $BG Try $NC" " $RED Nope! $NC" " $RED Challange $BG Accepted $NC" " $RED Ha $BG Ha! $NC" " $RED You $BG Funny $NC" " $RED Really? $NC" " $RED I Love $BG FOSS $NC" " $RED You're the $BG Boss $NC" "$BG$TC T $NC$BG$TC O $NC$BG$TC O $NC$BG$TC L $NC $BG B $NC $BG O $NC $BG X $NC")
    echo -e "${arr["$((RANDOM % ${#arr[@]}))"]}"
}

# Main UI code is below
function main() {

    # Define Menu entries which will be run with the echo command
    E0="\e[1mQ\e[0muit"
    E1="\e[1mP\e[0mackage manager UI"
    E2="System \e[1mI\e[0mnformation"
    E3="\e[1mH\e[0mardware & Drivers"
    E4="System & Settings"
    E5="\e[1mF\e[0mile Manager"
    E6="File \e[1mS\e[0mearch"
    E7="Fast File Compression"
    E8="CLI Trans\e[1ml\e[0mator"
    E9="\e[1mW\e[0meb Browser"
    E10="\e[1mT\e[0mask Manager"
    E11="\e[1mC\e[0mpu Frequency Info"
    E12="System \e[1mD\e[0miagnosis"
    E13="Website Status Check"
    E14="\e[1mM\e[0music Player"

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

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

        # Check if Pacui is installed for a different text
        if ! [ -x "$(command -v pacui)" ] && [ "$PACUIFAILEDINSTALL" == "1" ]; then
            DISABLEPACUI=2
        else
            if [ "$PACUIFROMSOURCE" == "1" ]; then
                DISABLEPACUI=3
            else
                if ! [ -x "$(command -v pacui)" ]; then
                    DISABLEPACUI=1
                fi
            fi
        fi

        # Check if "mhwd" is installed for a different text
        if ! [ -x "$(command -v mhwd)" ]; then
            DISABLEMHWD=1
        fi

        echo
        echo -e "                      $BG$TC T $NC$BG$TC O $NC$BG$TC O $NC$BG$TC L $NC $BG B $NC $BG O $NC $BG X $NC"
        echo -e " $TC+----------------------------------------------------------------+$NC"
        #echo -e " $TC|$NC    $BG 1 $NC $E1      $TC|$NC    $BG 2 $NC $E2     $TC|$NC"
        [[ "$DISABLEPACUI" == "0" ]] && echo -e " $TC|$NC    $BG 1 $NC $E1      $TC|$NC    $BG 2 $NC $E2     $TC|$NC"
        [[ "$DISABLEPACUI" == "1" ]] && echo -e " $TC|$NC    $BG 1 $NC [PacUI] (Not Installed) $TC|$NC    $BG 2 $NC $E2     $TC|$NC"
        [[ "$DISABLEPACUI" == "2" ]] && echo -e " $TC|$NC    $BG$TC T $NC$BG$TC O $NC$BG$TC O $NC$BG$TC L $NC $BG B $NC $BG O $NC $BG X $NC    $TC|$NC    $BG 2 $NC $E2     $TC|$NC"
        [[ "$DISABLEPACUI" == "3" ]] && echo -e " $TC|$NC    $BG 1 $NC $E1      $TC|$NC    $BG 2 $NC $E2     $TC|$NC"
        echo -e " $TC|$NC--------------------------------$TC|$NC-------------------------------$TC|$NC"
        [[ "$DISABLEMHWD" == "0" ]] && echo -e " $TC|$NC    $BG 3 $NC $E3      $TC|$NC    $BG 4 $NC $E4      $TC|$NC"
        [[ "$DISABLEMHWD" == "1" ]] && echo -e " $TC|$NC    $BG 3 $NC [mhwd] (Not Installed)  $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 T $NC $E10           $TC|$NC"
        echo -e " $TC|$NC--------------------------------$TC|$NC-------------------------------$TC|$NC"
        echo -e " $TC|$NC    $BG C $NC $E11      $TC|$NC    $BG D $NC $E12       $TC|$NC"
        echo -e " $TC|$NC--------------------------------$TC|$NC-------------------------------$TC|$NC"
        echo -e " $TC|$NC    $BG U $NC $E13    $TC|$NC    $BG M $NC $E14           $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

        # test, whether "choice" fits any of the following numbers or letters
        case "$choice" in

        1 | P | p)
            [[ "$DISABLEPACUI" == "0" ]] && package_manager_ui
            [[ "$DISABLEPACUI" == "1" ]] && package_manager_ui
            [[ "$DISABLEPACUI" == "3" ]] && sh "$PACUITMPDIR/pacui"
            ;;
        2 | I | i)
            printf '\33[H\33[2J'
            sysinfo
            echo
            echo -e " $RED Displaying System Information. To return to ToolBox press ENTER $NC"
            # wait for input, e.g. by pressing ENTER:
            read -r
            ;;
        3 | H | h)
            [[ "$DISABLEMHWD" == "0" ]] && mhwd-tui
            ;;
        4)
            system-menu
            ;;
        5 | F | f)
            printf '\33[H\33[2J'
            cli_filemanager
            ;;
        6 | S | s)
            cd || exit
            file_finder
            echo
            ;;
        7)
            printf '\33[H\33[2J'
            fastcompress-tui
            echo
            ;;
        8 | L | l)
            printf '\33[H\33[2J'
            gawk -f <(curl -Ls git.io/translate) -- -shell
            ;;
        9 | W | w)
            printf '\33[H\33[2J'
            cli_browser
            echo
            echo -e " $RED Displaying Web Browser. To return to ToolBox press ENTER $NC"
            # wait for input, e.g. by pressing ENTER:
            read -r
            ;;
        T | t)
            printf '\33[H\33[2J'
            taskmanager
            ;;
        C | c)
            printf '\33[H\33[2J'
            freqinfo
            ;;
        D | d)
            diagnosis-menu
            ;;
        U | u)
            printf '\33[H\33[2J'
            isitup
            echo
            echo -e " $RED Displaying Website Status Check. To return to ToolBox press ENTER $NC"
            read -r
            ;;
        M | m)
            printf '\33[H\33[2J'
            music
            ;;
        +)
            printf '\33[H\33[2J'
            randArrayElement "ARRAYISO[@]"
            sleep 1
            ;;
        0 | Q | q)
            [[ "$PACUIFROMSOURCE" == "1" ]] && rm -rf "$PACUITMPDIR" &>/dev/null
            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 # close case-loop

    done
    # close while-loop
}
main
