#!/bin/bash

: <<'DISCLAIMER'

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

This script is licensed under the terms of the MIT license.
Unless otherwise noted, code reproduced herein
was written for this script.

- The Pimoroni Crew -

DISCLAIMER

# script control variables

productname="Pimoroni Dashboard" # the name of the product to install
prodversion="1.0.5" # version of the present implementation
prodbuild="1806111450" # build for testing purposes
scriptname="pimoroni" # the name of this script
spacereq=50 # minimum size required on root partition in MB
debugmode="no" # whether the script should use debug routines
debuguser="none" # optional test git user to use in debug mode
debugpoint="none" # optional git repo branch or tag to checkout
forcesudo="no" # whether the script requires to be ran with root privileges
promptreboot="no" # whether the script should always prompt user to reboot
customcmd="no" # whether to execute commands specified before exit
armhfonly="yes" # whether the script is allowed to run on other arch
armv6="yes" # whether armv6 processors are supported
armv7="yes" # whether armv7 processors are supported
armv8="yes" # whether armv8 processors are supported
raspbianonly="no" # whether the script is allowed to run on other OSes
osreleases=( "Raspbian" "Kano" "Mate" "PiTop" "RetroPie" ) # list os-releases supported
oswarning=( "Debian" ) # list experimental os-releases
osdeny=( "Darwin" "Kali" "Linaro" "OSMC" "Ubuntu" "Volumio" ) # list os-releases specifically disallowed

declare -A deblibpairs=( \
["buttonshim"]="buttonshim" \
["automationhat"]="automationhat" \
["blinkt"]="blinkt" \
["displayotron"]="dot3k" \
["drumhat"]="drumhat" \
["envirophat"]="envirophat" \
["explorerhat"]="explorerhat" \
["fourletterphat"]="fourletterphat" \
["inkyphat"]="inkyphat" \
["microdotphat"]="microdotphat" \
["mote"]="mote" \
["motephat"]="motephat" \
["pantilthat"]="pantilthat" \
["phatbeat"]="phatbeat" \
["pianohat"]="pianohat" \
["pibrella"]="pibrella" \
["piglow"]="piglow" \
["propellerhat"]="p1" \
["rainbowhat"]="rainbowhat" \
["scrollphat"]="scrollphat" \
["scrollphathd"]="scrollphathd" \
["skywriterhat"]="skywriter" \
["touchphat"]="touchphat" \
["unicornhat"]="unicornhat" \
["unicornhathd"]="unicornhathd" )

# setup variables

FORCE=$1
ASK_TO_REBOOT=false
CURRENT_SETTING=false
MIN_INSTALL=false
FAILED_PKG=false
REMOVE_PKG=false
UPDATE_DB=false

DESKTOP_FILE="~/Desktop/pimoroni-dashboard.desktop"
DESKTOP_APP_FILE="/usr/share/applications/pimoroni-dashboard.desktop"
DESKTOP_ICON="/usr/share/pixmaps/pimoroni-dashboard.png"
DASHBOARD_SCRIPT="/usr/bin/pimoroni-dashboard"

RASPOOL="http://mirrordirector.raspbian.org/raspbian/pool"
RPIPOOL="http://archive.raspberrypi.org/debian/pool"
DEBPOOL="http://ftp.debian.org/debian/pool"
GETPOOL="https://get.pimoroni.com"

# function define

confirm() {
    if [ "$FORCE" == '-y' ]; then
        true
    else
        read -r -p "$1 [y/N] " response < /dev/tty
        if [[ $response =~ ^(yes|y|Y)$ ]]; then
            true
        else
            false
        fi
    fi
}

prompt() {
        read -r -p "$1 [y/N] " response < /dev/tty
        if [[ $response =~ ^(yes|y|Y)$ ]]; then
            true
        else
            false
        fi
}

success() {
    echo -e "$(tput setaf 2)$1$(tput sgr0)"
}

inform() {
    echo -e "$(tput setaf 6)$1$(tput sgr0)"
}

warning() {
    echo -e "$(tput setaf 1)$1$(tput sgr0)"
}

newline() {
    echo ""
}

progress() {
    count=0
    until [ $count -eq 7 ]; do
        echo -n "..." && sleep 1
        ((count++))
    done;
    if ps -C $1 > /dev/null; then
        echo -en "\r\e[K" && progress $1
    fi
}

sudocheck() {
    if [ $(id -u) -ne 0 ]; then
        echo -e "Install must be run as root. Try 'sudo ./$scriptname'\n"
        exit 1
    fi
}

sysclean() {
    sudo apt-get clean && sudo apt-get autoclean
    sudo apt-get -y autoremove &> /dev/null
}

sysupdate() {
    if ! $UPDATE_DB; then
        echo "Updating apt indexes..." && progress apt-get &
        sudo apt-get update 1> /dev/null || { warning "Apt failed to update indexes!" && exit 1; }
        sleep 3 && UPDATE_DB=true
    fi
}

sysupgrade() {
    sudo apt-get upgrade
    sudo apt-get clean && sudo apt-get autoclean
    sudo apt-get -y autoremove &> /dev/null
}

sysreboot() {
    warning "Some changes made to your system require"
    warning "your computer to reboot to take effect."
    echo
    if prompt "Would you like to reboot now?"; then
        sync && sudo reboot
    fi
}

arch_check() {
    IS_ARMHF=false
    IS_ARMv6=false

    if uname -m | grep -q "armv.l"; then
        IS_ARMHF=true
        if uname -m | grep -q "armv6l"; then
            IS_ARMv6=true
        fi
    fi
}

os_check() {
    IS_MACOSX=false
    IS_RASPBIAN=false
    IS_SUPPORTED=false
    IS_EXPERIMENTAL=false
    OS_NAME="Unknown"

    if uname -s | grep -q "Darwin"; then
        OS_NAME="Darwin" && IS_MACOSX=true
    elif cat /etc/os-release | grep -q "Kali"; then
        OS_NAME="Kali"
    elif [ -d ~/.kano-settings ] || [ -d ~/.kanoprofile ]; then
        OS_NAME="Kano"
    elif whoami | grep -q "linaro"; then
        OS_NAME="Linaro"
    elif [ -d ~/.config/ubuntu-mate ];then
        OS_NAME="Mate"
    elif [ -d ~/.pt-os-dashboard ] || [ -d ~/.pt-dashboard ] || [ -f ~/.pt-dashboard-config ]; then
        OS_NAME="PiTop"
    elif command -v emulationstation > /dev/null; then
        OS_NAME="RetroPie"
    elif cat /etc/os-release | grep -q "OSMC"; then
        OS_NAME="OSMC"
    elif cat /etc/os-release | grep -q "volumio"; then
        OS_NAME="Volumio"
    elif cat /etc/os-release | grep -q "Raspbian"; then
        OS_NAME="Raspbian" && IS_RASPBIAN=true
    elif cat /etc/os-release | grep -q "Debian"; then
        OS_NAME="Debian"
    elif cat /etc/os-release | grep -q "Ubuntu"; then
        OS_NAME="Ubuntu"
    fi

    if [[ " ${osreleases[@]} " =~ " ${OS_NAME} " ]]; then
        IS_SUPPORTED=true
    fi
    if [[ " ${oswarning[@]} " =~ " ${OS_NAME} " ]]; then
        IS_EXPERIMENTAL=true
    fi
}

raspbian_check() {
    IS_SUPPORTED=false
    IS_EXPERIMENTAL=false

    if [ -f /etc/os-release ]; then
        if cat /etc/os-release | grep -q "/sid"; then
            IS_SUPPORTED=false && IS_EXPERIMENTAL=true
        elif cat /etc/os-release | grep -q "buster"; then
            IS_SUPPORTED=false && IS_EXPERIMENTAL=true
        elif cat /etc/os-release | grep -q "stretch"; then
            IS_SUPPORTED=false && IS_EXPERIMENTAL=false
        elif cat /etc/os-release | grep -q "jessie"; then
            IS_SUPPORTED=true && IS_EXPERIMENTAL=false
        elif cat /etc/os-release | grep -q "wheezy"; then
            IS_SUPPORTED=true && IS_EXPERIMENTAL=false
        else
            IS_SUPPORTED=false && IS_EXPERIMENTAL=false
        fi
    fi
}

home_dir() {
    if [ $EUID -ne 0 ]; then
        if $IS_MACOSX; then
            USER_HOME=$(dscl . -read /Users/$USER NFSHomeDirectory | cut -d: -f2)
        else
            USER_HOME=$(getent passwd $USER | cut -d: -f6)
        fi
    else
        warning "Running as root, please log in as a regular user with sudo rights!"
        echo && exit 1
    fi
}

space_chk() {
    if command -v stat > /dev/null && ! $IS_MACOSX; then
        if [ $spacereq -gt $(($(stat -f -c "%a*%S" /)/10**6)) ];then
            echo
            warning  "There is not enough space left to proceed with  installation"
            if confirm "Would you like to attempt to expand your filesystem?"; then
                curl -sS $GETPOOL/expandfs | sudo bash && exit 1
            else
                echo && exit 1
            fi
        fi
    fi
}

timestamp() {
    date +%Y%m%d-%H%M
}

check_network() {
    sudo ping -q -w 10 -c 1 8.8.8.8 | grep "received, 0" &> /dev/null && return 0 || return 1
}

launch_url() {
    check_network || (error_box "You don't appear to be connected to the internet, please check your connection and try again!" && exit 1)
    if command -v xdg-open > /dev/null; then
        xdg-open "$1" && return 0
    else
        error_box "There was an error attempting to launch your browser!"
    fi
}

get_install() {
    check_network || (error_box "You don't appear to be connected to the internet, please check your connection and try again!" && exit 1)
    if [ "$1" != diagnostic ];then
        sysupdate && UPDATE_DB=true
    fi
    if ! command -v curl > /dev/null; then
        apt_pkg_install "curl"
    fi
    curl -sS https://get.pimoroni.com/$1 | bash -s - "-y" $2
    read -p "Press Enter to continue..." < /dev/tty
}

apt_pkg_req() {
    APT_CHK=$(dpkg-query -W -f='${Status}\n' "$1" 2> /dev/null | grep "install ok installed")

    if [ "" == "$APT_CHK" ]; then
        echo "$1 is required"
        true
    else
        echo "$1 is already installed"
        false
    fi
}

apt_pkg_install() {
    echo "Installing $1..."
    sudo apt-get --yes install "$1" 1> /dev/null || { inform "Apt failed to install $1!\nFalling back on pypi..." && return 1; }
}

apt_deb_chk() {
    BEFORE=$(dpkg-query -W "$1" 2> /dev/null)
    sudo apt-get --yes install "$1" &> /dev/null || return 1
    AFTER=$(dpkg-query -W "$1" 2> /dev/null)
    if [ "$BEFORE" == "$AFTER" ]; then
        echo "$1 is already the newest version"
    else
        echo "$1 was successfully upgraded"
    fi
}

apt_deb_install() {
    echo "Installing $1..."
    if [[ "$1" != *".deb"* ]]; then
        sudo apt-get --yes install "$1" &> /dev/null || inform "Apt failed to install $1!\nFalling back on pypi..."
        dpkg-query -W -f='${Status}\n' "$1" 2> /dev/null | grep "install ok installed"
    else
        DEBDIR=`mktemp -d /tmp/pimoroni.XXXXXX`
        cd $DEBDIR
        wget "$GETPOOL/resources/$1" &> /dev/null
        sudo dpkg -i "$DEBDIR/$1" | grep "Installing $1"
    fi
}

pip_cmd_chk() {
    if command -v pip2 > /dev/null; then
        PIP2_BIN="pip2"
    elif command -v pip-2.7 > /dev/null; then
        PIP2_BIN="pip-2.7"
    elif command -v pip-2.6 > /dev/null; then
        PIP2_BIN="pip-2.6"
    else
        PIP2_BIN="pip"
    fi
    if command -v pip3 > /dev/null; then
        PIP3_BIN="pip3"
    elif command -v pip-3.3 > /dev/null; then
        PIP3_BIN="pip-3.3"
    elif command -v pip-3.2 > /dev/null; then
        PIP3_BIN="pip-3.2"
    fi
}

pip2_lib_req() {
    PIP2_CHK=$($PIP2_BIN list 2> /dev/null | grep -i "$1")

    if [ -z "$PIP2_CHK" ]; then
        true
    else
        false
    fi
}

pip3_lib_req() {
    PIP3_CHK=$($PIP3_BIN list 2> /dev/null | grep -i "$1")

    if [ -z "$PIP3_CHK" ]; then
        true
    else
        false
    fi
}

lib_chk() {
    sysupdate && pip_cmd_chk
    echo -e "\nChecking for installed libraries..."
    for debpkg in "${!deblibpairs[@]}"; do
        progress 3
        if command -v $PIP2_BIN > /dev/null && ! pip2_lib_req "${deblibpairs[$debpkg]}"; then
            if ! apt_deb_chk "python-$debpkg"; then
                PIP2_MSG=$(sudo -H $PIP2_BIN install -U "${deblibpairs[$debpkg]}" \
                | grep -i -e "installed ${deblibpairs[$debpkg]}" -i -e "up-to-date: ${deblibpairs[$debpkg]}")
                if [[ "$PIP2_MSG" == *"up-to-date"* ]]; then
                    echo "${deblibpairs[$debpkg]} for Python 2 is already the newest version"
                else
                    echo "${deblibpairs[$debpkg]} for Python 2 was successfully upgraded"
                fi
            else
                sudo $PIP2_BIN uninstall -y "$debpkg" &> /dev/null
            fi
        fi
        if command -v $PIP3_BIN > /dev/null && ! pip3_lib_req "${deblibpairs[$debpkg]}"; then
            if ! apt_deb_chk "python3-$debpkg"; then
                PIP3_MSG=$(sudo -H $PIP3_BIN install -U "${deblibpairs[$debpkg]}" \
                | grep -i -e "installed ${deblibpairs[$debpkg]}" -i -e "up-to-date: ${deblibpairs[$debpkg]}")
                if [[ "$PIP3_MSG" == *"up-to-date"* ]]; then
                    echo "${deblibpairs[$debpkg]} for Python 3 is already the newest version"
                else
                    echo "${deblibpairs[$debpkg]} for Python 3 was successfully upgraded"
                fi
            else
                sudo $PIP3_BIN uninstall -y "$debpkg" &> /dev/null
            fi
        fi
    done
    inform "\nall libraries are now up-to-date!\n"
}

save_stdout() {
    if [ "$1" == "diagnostic" ]; then
        savename="$(timestamp)-info.txt"
        savedir=$HOME
    else
        savename="pimoroni-log.txt"
        savedir="/tmp"
    fi

    if [ -n "$xdisplay" ]; then
        if [ "$1" != "logfile" ]; then
            get_install "$1" 2>&1 | tee "$savedir/$savename"
            sed -i "/Press Enter/d" "$savedir/$savename"
        fi
        if [ "$1" == "logfile" ] || [ "$1" == "diagnostic" ]; then
            rm ~/Desktop/"$savename" &> /dev/null
            mv "$savedir/$savename" ~/Desktop/ &> /dev/null
            info_box "The file has been saved to the Desktop!"
        fi
    else
        if [ "$1" != "logfile" ]; then
            get_install "$1" 2>&1 | tee "$savedir/$savename"
            sed -i "/Press Enter/d" "$savedir/$savename"
        fi
        if [ "$1" == "logfile" ] || [ "$1" == "diagnostic" ]; then
            rm ~/"$savename" &> /dev/null
            mv "$savedir/$savename" ~/ &> /dev/null
            info_box "The file has been saved to your home folder!"
        fi
    fi
}

save_snap() {
    if ! command -v scrot > /dev/null; then
        warning "scrot is not installed"
        echo "try: sudo apt-get install scrot"
    elif [ -z "$xdisplay" ]; then
        error_box "X is not running, we can't take screenshots, sorry!"
    else
        info_box "\
Please hit enter and then select the area you would like\n\
to screenshot by drawing a rectangle with your mouse.\n\n\
Make sure to move this window out of the way first!\n\n\
This screenshot will be stored on your desktop,\n\
from where you can share it with us or with the world!"
        echo "Taking screenshot..."
        echo "Draw a rectangle around your subject."
        scrot -s ~/Desktop/%Y%m%d-%H%M-snap.png
        info_box "Success, your screenshot has been saved to the Desktop!"
    fi
}

self_update() {
    check_network || (error_box "You don't appear to be connected to the internet, please check your connection and try again!" && exit 1)
    VCHK=$(curl -sS "$GETPOOL/dashboard" | grep -e "^debpackage=" | grep -e "$prodversion")
    if [ -z "$VCHK" ]; then
        if [ -n "$xdisplay" ]; then
            status_box "Downloading update"
        else
            status_box "An update is available, click OK to download it."
        fi
        \curl -sS https://get.pimoroni.com/dashboard | bash -s - "-y"
        read -p "Press Enter to continue..." < /dev/tty
        if [ -n "$xdisplay" ]; then
            status_box "Restarting!"
        else
            status_box "Click OK to restart the program and complete the update procedure."
        fi
        sleep 1 && pimoroni-dashboard -y
        exit 0 # must be on separate line
    fi
}

about_box() {
    if [ -n "$xdisplay" ]; then
        zenity --height=128 --width=256 --info --text "\n$productname\nversion $prodversion\nbuild $prodbuild" 2> /dev/null
    else
        whiptail --msgbox "$productname\nversion $prodversion\n$prodbuild" $BOXHEIGHT $(($BOXWIDTH-10))
    fi
}

confirm_box() {
    if [ -n "$xdisplay" ]; then
        zenity --height=128 --width=512 --question --text "$1" 2> /dev/null
    else
        whiptail --yesno "$1" $BOXHEIGHT $(($BOXWIDTH-10))
    fi
}

info_box() {
    if [ -n "$xdisplay" ]; then
        zenity --info --text "$1" --height=$BOX_MIN_HEIGHT --width=$BOXWIDTH 2> /dev/null
    else
        whiptail --msgbox "$1" $BOXHEIGHT $(($BOXWIDTH-10))
    fi
}

status_box() {
    if [ -n "$xdisplay" ]; then
        zenity --info --timeout=1 --text "$1" --height=$BOX_MIN_HEIGHT --width=$(($BOXWIDTH-256)) 2> /dev/null
    else
        whiptail --msgbox "$1" $BOXHEIGHT $(($BOXWIDTH-10))
    fi
}

error_box() {
    if [ -n "$xdisplay" ]; then
        zenity --height=128 --width=512 --error --text "$1" 2> /dev/null
    else
        whiptail --msgbox "$1" $BOXHEIGHT $(($BOXWIDTH-10))
    fi
}

box_size() {
    if [ -n "$xdisplay" ]; then
        BOXHEIGHT=320
        BOXWIDTH=512
        BOX_MIN_HEIGHT=64
    else
        BOXHEIGHT=17
        BOXWIDTH=$(tput cols)
        if [ -z "$BOXWIDTH" ] || [ "$BOXWIDTH" -lt 60 ]; then
            BOXWIDTH=80
        fi
        if [ "$BOXWIDTH" -gt 178 ]; then
            BOXWIDTH=120
        fi
        BOX_MENU_HEIGHT=$(($BOXHEIGHT-7))
    fi
}

# menu define

main_menu() {

TITLE="$productname"
MAINLIST="\
1/My Pimoroni product is a HAT/\
2/My Pimoroni product is a pHAT/\
3/My product is something else/\
4/Pimoroni kits and projects/\
5/Update all installed libraries/\
6/View product documentation/\
7/I have a problem and need help/\
8/Take me to the Pimoroni shop"

    if [ -n "$xdisplay" ]; then
        MAIN=$(zenity --title="$TITLE" --list \
            --column="Option" --column="Description" \
            --cancel-label=Quit --ok-label=Select \
            --height=$BOXHEIGHT --width=$BOXWIDTH \
            $MAINLIST 2> /dev/null
        )
    else
        MAIN=$(whiptail --title "$TITLE" --menu "" \
            --cancel-button Quit --ok-button Select \
            $BOXHEIGHT $(($BOXWIDTH-10)) $BOX_MENU_HEIGHT \
            $MAINLIST 3>&1 1>&2 2>&3
        )
    fi

    RETURN=$?
    if [ $RETURN -eq 1 ]; then
        exit 1
    elif [ $RETURN -eq 0 ]; then
        case "$MAIN" in
            '')exit 0 ;;
            1) hat_menu ;;
            2) phat_menu ;;
            3) board_menu ;;
            4) kits_menu ;;
            5) lib_chk ;;
            6) launch_url "http://docs.pimoroni.com" & ;;
            7) launch_url "https://shop.pimoroni.com" & ;;
            8) util_menu ;;
            *) error_box "Error: unrecognized option";;
        esac ||error_box "There was an error running option $MAIN"
    fi
}

board_menu() {

TITLE="$productname"
ADDLIST="\
1/Blinkt!/\
2/Button SHIM/\
3/Display-o-Tron 3000/\
4/Flotilla/\
5/HyperPixel/\
6/Mote/\
7/OnOff SHIM/\
8/Pibrella/\
9/Picade PCB/\
10/Piglow/\
11/Skywriter/\
12/Zero LiPo"

    if [ -n "$xdisplay" ]; then
        BOARD=$(zenity --title="$TITLE" --list \
            --column="Option" --column="Description" \
            --cancel-label=Back --ok-label=Select \
            --height=$BOXHEIGHT --width=$BOXWIDTH \
            $ADDLIST 2> /dev/null
        )
    else
        BOARD=$(whiptail --title "$TITLE" --menu "" \
            --cancel-button Back --ok-button Select \
            $BOXHEIGHT $(($BOXWIDTH-10)) $BOX_MENU_HEIGHT \
            $ADDLIST 3>&1 1>&2 2>&3
        )
    fi

    RETURN=$?
    if [ $RETURN -eq 1 ]; then
        return 0
    elif [ $RETURN -eq 0 ]; then
        case "$BOARD" in
            1) get_install blinkt ;;
            2) get_install buttonshim ;;
            3) get_install dot3k ;;
            4) get_install flotilla ;;
            5) get_install hyperpixel ;;
            6) get_install mote ;;
            7) get_install onoffshim ;;
            8) get_install pibrella ;;
            9) get_install picadefw ;;
            10) get_install piglow ;;
            11) get_install skywriter ;;
            12) get_install zerolipo ;;
            *) error_box --text "Error: unrecognized option";;
        esac ||error_box "There was an error running option $BOARD"
    fi
}

hat_menu() {

TITLE="$productname"
HATLIST="\
1/Automation HAT/\
2/Display-o-Tron HAT/\
3/Drum HAT/\
4/Explorer HAT/\
5/Pan-Tilt HAT/\
6/Piano HAT/\
7/Picade HAT/\
8/Propeller HAT/\
9/Rainbow HAT/\
10/Skywriter HAT/\
11/Unicorn HAT/\
12/Unicorn HAT HD"

    if [ -n "$xdisplay" ]; then
        HAT=$(zenity --title="$TITLE" --list \
            --column="Option" --column="Description" \
            --cancel-label=Back --ok-label=Select \
            --height=$BOXHEIGHT --width=$BOXWIDTH \
            $HATLIST 2> /dev/null
        )
    else
        HAT=$(whiptail --title "$TITLE" --menu "" \
            --cancel-button Back --ok-button Select \
            $BOXHEIGHT $(($BOXWIDTH-10)) $BOX_MENU_HEIGHT \
            $HATLIST 3>&1 1>&2 2>&3
        )
    fi

    RETURN=$?
    if [ $RETURN -eq 1 ]; then
        return 0
    elif [ $RETURN -eq 0 ]; then
        case "$HAT" in
            1) get_install automationhat ;;
            2) get_install displayotron ;;
            3) get_install drumhat ;;
            4) get_install explorerhat ;;
            5) get_install pantilthat ;;
            6) get_install pianohat ;;
            7) get_install picadehat ;;
            8) get_install propellerhat ;;
            9) get_install rainbowhat ;;
            10) get_install skywriter ;;
            11) get_install unicornhat ;;
            12) get_install unicornhathd ;;
            *) error_box "Error: unrecognized option";;
        esac ||error_box "There was an error running option $HAT"
    fi
}

phat_menu() {

TITLE="$productname"
PHATLIST="\
1/Automation pHAT/\
2/Enviro pHAT/\
3/ESP IoT pHAT/\
4/Explorer pHAT/\
5/Four Letter pHAT/\
6/Inky pHAT/\
7/Micro Dot pHAT/\
8/Mote pHAT/\
9/pHAT BEAT/\
10/pHAT DAC/\
11/Scroll pHAT/\
12/Scroll pHAT HD/\
13/Speaker pHAT/\
14/Touch pHAT/\
15/Unicorn pHAT"

    if [ -n "$xdisplay" ]; then
        PHAT=$(zenity --title="$TITLE" --list \
            --column="Option" --column="Description" \
            --cancel-label=Back --ok-label=Select \
            --height=$BOXHEIGHT --width=$BOXWIDTH \
            $PHATLIST 2> /dev/null
        )
    else
        PHAT=$(whiptail --title "$TITLE" --menu "" \
            --cancel-button Back --ok-button Select \
            $BOXHEIGHT $(($BOXWIDTH-10)) $BOX_MENU_HEIGHT \
            $PHATLIST 3>&1 1>&2 2>&3
        )
    fi

    RETURN=$?
    if [ $RETURN -eq 1 ]; then
        return 0
    elif [ $RETURN -eq 0 ]; then
        case "$PHAT" in
            1) get_install automationhat ;;
            2) get_install envirophat ;;
            3) get_install iotphat ;;
            4) get_install explorerhat ;;
            5) get_install fourletterphat ;;
            6) get_install inkyphat ;;
            7) get_install microdotphat ;;
            8) get_install motephat ;;
            9) get_install phatbeat ;;
            10) get_install phatdac ;;
            11) get_install scrollphat ;;
            12) get_install scrollphathd ;;
            13) get_install speakerphat ;;
            14) get_install touchphat ;;
            15) get_install unicornhat ;;
            *) error_box "Error: unrecognized option";;
        esac ||error_box "There was an error running option $PHAT"
    fi
}

kits_menu() {

TITLE="$productname"
ADDLIST="\
1/Starter Kit/\
2/Flotilla Kit/\
3/Mote Kit/\
4/Mood Light/\
5/OctoCam/\
6/Pirate Radio/\
7/Scroll Bot/\
8/Other projects"

    if [ -n "$xdisplay" ]; then
        KITS=$(zenity --title="$TITLE" --list \
            --column="Option" --column="Description" \
            --cancel-label=Back --ok-label=Select \
            --height=$BOXHEIGHT --width=$BOXWIDTH \
            $ADDLIST 2> /dev/null
        )
    else
        KITS=$(whiptail --title "$TITLE" --menu "" \
            --cancel-button Back --ok-button Select \
            $BOXHEIGHT $(($BOXWIDTH-10)) $BOX_MENU_HEIGHT \
            $ADDLIST 3>&1 1>&2 2>&3
        )
    fi

    RETURN=$?
    if [ $RETURN -eq 1 ]; then
        return 0
    elif [ $RETURN -eq 0 ]; then
        case "$KITS" in
            1) starter_menu ;;
            2) get_install flotilla ;;
            3) get_install mote ;;
            4) get_install unicornhat ;;
            5) launch_url "https://learn.pimoroni.com/tutorial/sandyj/motioneye-os-on-your-octocam" & ;;
            6) radio_menu ;;
            7) get_install scrollphathd ;;
            8) projects_menu ;;
            *) error_box --text "Error: unrecognized option";;
        esac ||error_box "There was an error running option $KITS"
    fi
}

projects_menu() {

TITLE="$productname"
ADDLIST="\
1/Audio projects/\
2/Misc projects"

    if [ -n "$xdisplay" ]; then
        PROJ=$(zenity --title="$TITLE" --list \
            --column="Option" --column="Description" \
            --cancel-label=Back --ok-label=Select \
            --height=$BOXHEIGHT --width=$BOXWIDTH \
            $ADDLIST 2> /dev/null
        )
    else
        PROJ=$(whiptail --title "$TITLE" --menu "" \
            --cancel-button Back --ok-button Select \
            $BOXHEIGHT $(($BOXWIDTH-10)) $BOX_MENU_HEIGHT \
            $ADDLIST 3>&1 1>&2 2>&3
        )
    fi

    RETURN=$?
    if [ $RETURN -eq 1 ]; then
        return 0
    elif [ $RETURN -eq 0 ]; then
        case "$PROJ" in
            1) audio_menu ;;
            2) misc_menu ;;
            *) error_box --text "Error: unrecognized option";;
        esac ||error_box "There was an error running option $PROJ"
    fi
}

misc_menu() {

TITLE="$productname"
ADDLIST="\
1/Access point roaming/\
2/Bluetooth file transfer/\
3/Clean shutdown"

    if [ -n "$xdisplay" ]; then
        MISC=$(zenity --title="$TITLE" --list \
            --column="Option" --column="Description" \
            --cancel-label=Back --ok-label=Select \
            --height=$BOXHEIGHT --width=$BOXWIDTH \
            $ADDLIST 2> /dev/null
        )
    else
        MISC=$(whiptail --title "$TITLE" --menu "" \
            --cancel-button Back --ok-button Select \
            $BOXHEIGHT $(($BOXWIDTH-10)) $BOX_MENU_HEIGHT \
            $ADDLIST 3>&1 1>&2 2>&3
        )
    fi

    RETURN=$?
    if [ $RETURN -eq 1 ]; then
        return 0
    elif [ $RETURN -eq 0 ]; then
        case "$MISC" in
            1) get_install wifiroaming ;;
            2) get_install bluetooth ;;
            3) get_install cleanshutdown ;;
            *) error_box --text "Error: unrecognized option";;
        esac ||error_box "There was an error running option $MISC"
    fi
}

audio_menu() {

TITLE="$productname"
ADDLIST="\
1/Airplay Speaker/\
2/Spotify Media Player/\
3/VLC Radio"

    if [ -n "$xdisplay" ]; then
        AUDIO=$(zenity --title="$TITLE" --list \
            --column="Option" --column="Description" \
            --cancel-label=Back --ok-label=Select \
            --height=$BOXHEIGHT --width=$BOXWIDTH \
            $ADDLIST 2> /dev/null
        )
    else
        AUDIO=$(whiptail --title "$TITLE" --menu "" \
            --cancel-button Back --ok-button Select \
            $BOXHEIGHT $(($BOXWIDTH-10)) $BOX_MENU_HEIGHT \
            $ADDLIST 3>&1 1>&2 2>&3
        )
    fi

    RETURN=$?
    if [ $RETURN -eq 1 ]; then
        return 0
    elif [ $RETURN -eq 0 ]; then
        case "$AUDIO" in
            1) get_install airdac ;;
            2) get_install spotipy ;;
            3) get_install vlcradio ;;
            *) error_box --text "Error: unrecognized option";;
        esac ||error_box "There was an error running option $AUDIO"
    fi
}

radio_menu() {

TITLE="$productname"
ADDLIST="\
1/Airplay Speaker/\
2/Spotify Media Player/\
3/VLC Radio"

    if [ -n "$xdisplay" ]; then
        RADIO=$(zenity --title="$TITLE" --list \
            --column="Option" --column="Description" \
            --cancel-label=Back --ok-label=Select \
            --height=$BOXHEIGHT --width=$BOXWIDTH \
            $ADDLIST 2> /dev/null
        )
    else
        RADIO=$(whiptail --title "$TITLE" --menu "" \
            --cancel-button Back --ok-button Select \
            $BOXHEIGHT $(($BOXWIDTH-10)) $BOX_MENU_HEIGHT \
            $ADDLIST 3>&1 1>&2 2>&3
        )
    fi

    RETURN=$?
    if [ $RETURN -eq 1 ]; then
        return 0
    elif [ $RETURN -eq 0 ]; then
        case "$RADIO" in
            1) get_install airdac ;;
            2) get_install spotipy ;;
            3) get_install vlcradio ;;
            *) error_box --text "Error: unrecognized option";;
        esac ||error_box "There was an error running option $RADIO"
    fi
}

starter_menu() {

TITLE="$productname"
ADDLIST="\
1/Getting started/\
2/Join the Pimoroni forums"

    if [ -n "$xdisplay" ]; then
        START=$(zenity --title="$TITLE" --list \
            --column="Option" --column="Description" \
            --cancel-label=Back --ok-label=Select \
            --height=$BOXHEIGHT --width=$BOXWIDTH \
            $ADDLIST 2> /dev/null
        )
    else
        START=$(whiptail --title "$TITLE" --menu "" \
            --cancel-button Back --ok-button Select \
            $BOXHEIGHT $(($BOXWIDTH-10)) $BOX_MENU_HEIGHT \
            $ADDLIST 3>&1 1>&2 2>&3
        )
    fi

    RETURN=$?
    if [ $RETURN -eq 1 ]; then
        return 0
    elif [ $RETURN -eq 0 ]; then
        case "$START" in
            1) get_install getstarted ;;
            2) launch_url "http://forums.pimoroni.com" & ;;
            *) error_box --text "Error: unrecognized option";;
        esac ||error_box "There was an error running option $START"
    fi
}

util_menu() {

TITLE="$productname"
UTILIST="\
1/About this program/\
2/Gather system info/\
3/Update my Pi software/\
4/Help me make a screenshot/\
5/Take me to the support forums"

    if [ -n "$xdisplay" ]; then
        UTIL=$(zenity --title="$TITLE" --list \
            --column="Option" --column="Description" \
            --cancel-label=Back --ok-label=Select \
            --height=$BOXHEIGHT --width=$BOXWIDTH \
            $UTILIST 2> /dev/null
        )
    else
        UTIL=$(whiptail --title "$TITLE" --menu "" \
            --cancel-button Back --ok-button Select \
            $BOXHEIGHT $(($BOXWIDTH-10)) $BOX_MENU_HEIGHT \
            $UTILIST 3>&1 1>&2 2>&3
        )
    fi

    RETURN=$?
    if [ $RETURN -eq 1 ]; then
        return 0
    elif [ $RETURN -eq 0 ]; then
        case "$UTIL" in
            1) about_box ;;
            2) save_stdout diagnostic ;;
            3) get_install uptodate ;;
            4) save_snap ;;
            5) launch_url "http://forums.pimoroni.com" & ;;
            *) error_box "Error: unrecognized option";;
        esac ||error_box "There was an error running option $UTIL"
    fi
}

# checks and init

arch_check
os_check
space_chk

if [ $debugmode != "no" ]; then
    echo "USER_HOME is $USER_HOME"
    echo "OS_NAME is $OS_NAME"
    echo "IS_SUPPORTED is $IS_SUPPORTED"
    echo "IS_EXPERIMENTAL is $IS_EXPERIMENTAL"
    echo
fi

if ! $IS_ARMHF; then
    warning "This hardware is not supported, sorry!"
    warning "Config files have been left untouched\n"
    exit 1
fi

if $IS_ARMv8 && [ $armv8 == "no" ]; then
    warning "Sorry, your CPU is not supported by this installer\n"
    exit 1
elif $IS_ARMv7 && [ $armv7 == "no" ]; then
    warning "Sorry, your CPU is not supported by this installer\n"
    exit 1
elif $IS_ARMv6 && [ $armv6 == "no" ]; then
    warning "Sorry, your CPU is not supported by this installer\n"
    exit 1
fi

if [ $raspbianonly == "yes" ] && ! $IS_RASPBIAN;then
    warning "This script is intended for Raspbian on a Raspberry Pi!\n"
    exit 1
fi

if $IS_RASPBIAN; then
    raspbian_check
    if ! $IS_SUPPORTED && ! $IS_EXPERIMENTAL; then
        warning "\n--- Warning ---\n"
        echo "The $productname installer"
        echo "does not work on this version of Raspbian."
        echo "Check https://github.com/$gitusername/$gitreponame"
        echo "for additional information and support" && echo
        exit 1
    fi
fi

if ! $IS_SUPPORTED && ! $IS_EXPERIMENTAL; then
    warning "Your operating system is not supported, sorry!\n"
    exit 1
fi

if $IS_EXPERIMENTAL; then
    warning "Support for your operating system is experimental. Please visit"
    warning "forums.pimoroni.com if you experience issues with this product.\n"
fi

if [ $forcesudo == "yes" ]; then
    sudocheck
fi

home_dir && WORKING_DIR="$USER_HOME/Pimoroni"
[ -d $WORKING_DIR ] || mkdir $WORKING_DIR
cd $WORKING_DIR

xdisplay="$DISPLAY"

if ! command -v zenity > /dev/null || [ $debugmode == "yes" ]; then
    xdisplay=""
fi

box_size

# program start

if [ -n "$1" ] && [ "$1" != '-y' ]; then
    UPDATE_DB=true
    get_install "$1" && exit 0
elif [ "$1" != '-y' ]; then
    info_box "\
This handy tool will help you get started with Pimoroni products.\n\
Simply pick the add-on board you want to set up from the list,\n\
hit select and we'll walk you through the install process in a\n\
few easy steps. Enjoy!\n\n\
The Pimoroni Crew"
    self_update
fi

listIFS="$IFS";
IFS="/"

while true; do
    main_menu
done

IFS=$listIFS

exit 0
