#!/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="na" # the name of the product to install
scriptname="rpihwinfo" # the name of this script
spacereq=1 # 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
mininstall="no" # whether the script enforces minimum install routine
customcmd="yes" # 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=( "Debian" "Kali" "Linaro" "Mate" "PiTop" "OSMC" "Raspbian" "RetroPie" "Ubuntu" ) # list os-releases supported
oswarning=() # list experimental os-releases
osdeny=( "Darwin" ) # list os-releases specifically disallowed

# setup variables

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

AUTOSTART=~/.config/lxsession/LXDE-pi/autostart
BOOTCMD=/boot/cmdline.txt
CONFIG=/boot/config.txt
APTSRC=/etc/apt/sources.list
INITABCONF=/etc/inittab
BLACKLIST=/etc/modprobe.d/raspi-blacklist.conf
LOADMOD=/etc/modules

# 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 "bullseye"; then
            IS_SUPPORTED=true && IS_EXPERIMENTAL=false
        elif cat /etc/os-release | grep -q "buster"; then
            IS_SUPPORTED=true && IS_EXPERIMENTAL=false
        elif cat /etc/os-release | grep -q "stretch"; then
            IS_SUPPORTED=true && 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
}

dt_check() {
    if [ -e $CONFIG ] && grep -q "^device_tree=$" $CONFIG; then
        DEVICE_TREE=false
    fi
}

i2c_check() {
    if [ -e $CONFIG ] && grep -q -E "^(device_tree_param|dtparam)=([^,]*,)*i2c(_arm)?(=(on|true|yes|1))?(,.*)?$" $CONFIG; then
        CURRENT_SETTING=true
    else
        CURRENT_SETTING=false
    fi
}

spi_check() {
    if [ -e $CONFIG ] && grep -q -E "^(device_tree_param|dtparam)=([^,]*,)*spi(=(on|true|yes|1))?(,.*)?$" $CONFIG; then
        CURRENT_SETTING=true
    else
        CURRENT_SETTING=false
    fi
}

get_init_sys() {
    if command -v systemctl > /dev/null && systemctl | grep -q '\-\.mount'; then
        SYSTEMD=1
    elif [ -f /etc/init.d/cron ] && [ ! -h /etc/init.d/cron ]; then
        SYSTEMD=0
    else
        echo "Unrecognised init system" && exit 1
    fi
}

get_hw_rev() {
    hwrid=$(grep "^Revision" /proc/cpuinfo | rev | cut -c 2-3 | rev)
    if [ "$hwrid" == "00" ] || [ "$hwrid" == "01" ];then # Pi 1
        hwver="$(grep "^Revision" /proc/cpuinfo | rev | cut -c 1-4 | rev)"
        if [ "$hwrid" == "00" ];then
            hwgen="1260" # P1
        elif [ "$hwrid" == "01" ];then
            hwgen="1400" # J8
        fi
    else
        hwver="$(grep "^Revision" /proc/cpuinfo | rev | cut -c 1-6 | rev)"
        if [ "$hwrid" == "04" ];then # Pi 2
            hwgen="2400"
        elif [ "$hwrid" == "08" ];then # Pi 3
            hwgen="3401"
        elif [ "$hwrid" == "09" ];then # Pi 0
            hwgen="0400"
        elif [ "$hwrid" == "0c" ];then # Pi 0 W
            hwgen="0401"
        else # Unknown
            hwgen="0000"
        fi
    fi
}

: <<'MAINSTART'

Perform all global variables declarations as well as function definition
above this section for clarity, thanks!

MAINSTART

# checks and init

dt_check
arch_check
os_check
get_hw_rev

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

# Main routine

newline

if [ -f /etc/os-release ]; then
    cat /etc/os-release | grep "PRETTY_NAME" | cut -c14- | rev | cut -c2- | rev
fi

if command -v uname > /dev/null; then
    echo "$(uname -s) kernel $(uname -r) on $(uname -m)"
fi

if [ -n $hwver ] && [ $hwver != "0000" ];then
    case $hwver in
       "0002"|"0003") echo "Revision match: Pi 1 Model B Rev 1.0";;
       "0004"|"0005"|"0006") echo "Revision match: Pi 1 Model B Rev 2.0";;
       "0007"|"0008"|"0009") echo "Revision match: Pi 1 Model A 256MB";;
       "000d"|"000e"|"000f") echo "Revision match: Pi 1 Model B 512MB";;
       "0010") echo "Revision match: Pi 1 Model B+ Rev 1.0";;
       "0011"|"0014") echo "Revision match: Compute Module 1";;
       "0012"|"0015") echo "Revision match: Pi 1 Model A+";;
       "0013") echo "Revision match: Pi 1 Model B+ Rev 1.2";;
       "a01040") echo "Revision match: Pi 2 Model B Rev 1.0";;
       "a01041"|"a21041") echo "Revision match: Pi 2 Model B Rev 1.1";;
       "a22042") echo "Revision match: Pi 2 Model B Rev 1.2";;
       "a02082"|"a22082"|"a32082") echo "Revision match: Pi 3 Model B Rev 1.2";;
       "a020a0") echo "Revision match: Compute Module 3";;
       "900092") echo "Revision match: Pi Zero Rev 1.2";;
       "900093"|"920093") echo "Revision match: Pi Zero Rev 1.3";;
       "9000c1"|"9200c1") echo "Revision match: Pi Zero W Rev 1.1";;
       *) warning "Revision unmatched";;
    esac
fi

if command -v aplay > /dev/null; then
    newline && aplay -l | grep "card"
    newline
fi

if lsusb | grep -v "hub" &> /dev/null; then
    echo "Devices on $(lsusb | grep "Bus 001 Device 001" | cut -c34-)"
    lsusb | grep -v "hub"
    maxpower=$(lsusb -v 2> /dev/null | grep "MaxPower" | grep "[0-9]0mA" | cut -c13- | tr -d "[:space:]" | sed "s|mA|mA +|")
    if [ -n "$maxpower" ]; then
        echo "Estimated MaxPower $maxpower 0mA"
    fi
    if [ -e $CONFIG ] && grep -q "^max_usb_current=1$" $CONFIG; then
        echo "Max USB current setting is active"
    fi
    newline
else
    echo "No USB devices found..." && newline
fi

if ls /dev/spi* &> /dev/null; then
    echo "SPI appears to be enabled"
fi

if ls /dev/i2c* &> /dev/null; then
    echo "I2C appears to be enabled"
    if lsmod | grep "i2c_dev" &> /dev/null && lsmod | grep "i2c_bcm2708" &> /dev/null; then
        echo "i2c_dev and i2c_bcm2708 loaded"
    fi
    if command -v i2cdetect > /dev/null; then
        newline && echo "I2C devices detected:"
        i2cdetect -y 1 | grep -e "--" | cut -c5- | grep -o -e "[0-z][0-z]" | sed "s|^|0x|"
    fi
fi

if [ -f /proc/device-tree/hat/product ]; then
    newline && echo "$(cat /proc/device-tree/hat/product) detected"
fi

newline

exit 0
