#!/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="I2C bus" # the name of the product to install
scriptname="i2c" # 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="yes" # 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=( "Raspbian" "Kano" "Mate" "OSMC" "PiTop" "RetroPie" "Volumio" ) # list os-releases supported
oswarning=( "Debian" "Ubuntu" ) # list experimental os-releases
osdeny=( "Darwin" "Kali" "Linaro" ) # 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
DTBODIR=/boot/overlays
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
}

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

# intro message

if [ $debugmode != "no" ]; then
    if [ $debuguser != "none" ]; then
        gitusername="$debuguser"
    fi
    if [ $debugpoint != "none" ]; then
        gitrepobranch="$debugpoint"
    fi
    inform "\nDEBUG MODE ENABLED"
    echo -e "git user $gitusername and $gitrepobranch branch/tag will be used\n"
else
    warning "This script should only be run on a Raspberry Pi\n"
    echo "This script will enable the I2C bus"
fi

# checks and init

dt_check

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

if confirm "Do you wish to continue?"; then

# environment preparation

    i2c_check

    if $DEVICE_TREE && ! $CURRENT_SETTING; then
        echo -e "\nDevice Tree Detected"
        echo -e "Enabling I2C...\n"
        if grep -q "^dtparam=i2c_arm=off" $CONFIG; then
            sudo sed -i "s|^dtparam=i2c_arm=off|dtparam=i2c_arm=on|" $CONFIG &> /dev/null
        elif grep -q "^#dtparam=i2c_arm=on" $CONFIG; then
            sudo sed -i "s|^#dtparam=i2c_arm=on|dtparam=i2c_arm=on|" $CONFIG &> /dev/null
        else
            echo "dtparam=i2c_arm=on" | sudo tee -a $CONFIG &> /dev/null
        fi
        if ! [ -e $BLACKLIST ]; then
            touch $BLACKLIST
        fi
        sudo sed -i "s|^\(blacklist[[:space:]]*i2c[-_]bcm2708\)|#\1|" $BLACKLIST &> /dev/null
        dtparam i2c_arm=on &> /dev/null
        inform "\nI2C Enabled"
        warning "Reboot required!\n"
        ASK_TO_REBOOT=true
    elif  ! $DEVICE_TREE && [ -e $BLACKLIST ] && grep -q "^blacklist[[:space:]]*i2c-bcm2708" $BLACKLIST; then
        echo -e "\nNo Device Tree Detected"
        echo -e "Enabling I2C..."
        echo -e "\nCommenting out Blacklist entry in\n$BLACKLIST"
        sudo sed -i "s|^blacklist[[:space:]]*i2c-bcm2708.*|#blacklist i2c-bcm2708|" $BLACKLIST &> /dev/null
        inform "\nI2C Enabled\n"
    else
        inform "I2C Already Enabled\n"
    fi
    if ! [ -e $LOADMOD ]; then
        touch $LOADMOD
    fi
    if ! grep -q "^i2c[-_]dev" $LOADMOD; then
        echo "i2c-dev" | sudo tee -a $LOADMOD &> /dev/null
    fi
    if ! grep -qe "i2c[-_]bcm2708" $LOADMOD; then
        echo "i2c-bcm2708" | sudo tee -a $LOADMOD &> /dev/null
    fi
    sudo modprobe -a i2c-bcm2708 i2c-dev
else
    echo -e "\nAborting...\n"
fi

exit 0
