#!/bin/bash
# sudo apt-get install htop  // used to check CPU
# sudo bash /boot/install_robotank.sh
    clear
    
    catch_exits() {  # function to clean up install files if script is aborted
        echo "Removing Robo-Tank Installation Files           ...takes less than 1 minute"
        sudo rm -r /boot/robotank/ &> /dev/null
        sudo rm -r "Robo-Tank_v6_5.zip" &> /dev/null
        exit 0
        printf "\n$(basename $0): exiting\n" 1>&2
        rm -rf $DIR
        exit 1
    }

    trap catch_exits 1 2 3 15 20  # run clean up if script is aborted

    cyan='\033[0;36m'
    NC='\033[0m' # No Color
    bold=$(tput bold)
    normal=$(tput sgr0)
    
    echo ""
    echo ""
    echo ""
    echo "This script will automate the installation process for Robo-Tank but does require attending."
    echo ""
    echo ""
    echo "This script does the following"
    echo "    * updates Raspberry Pi Operating System"
    echo "    * updates Raspberry Pi password"
    echo "    * prompts for hostname"
    echo "    * prompts for time zone"
    echo "    * enables time sync"
    echo "    * installs phpMyAdmin"
    echo "    * installs Apache2"
    echo "    * Integrate PHP with Apache"
    echo "    * installs MySQL"
    echo "    * installs Robo-Tank"
    echo "    * installs JSON library"
    echo "    * installs MySQL library"
    echo "    * installs libwebsockets library"
    echo "    * installs JsonCpp library"
    echo "    * installs libcurl library"
    echo "    * installs libquickmail library"
    echo "    * installs Robo-Tank service on Raspberry Pi"
    echo "    * removes Robo-Tank installation files"
    echo "    * generates website address to access Robo-Tank"
    echo "    * expands file system on microSD card"
    echo ""
    echo ""
    echo ""
    echo "Press enter to continue or press ${bold}Ctrl + C${normal} to abort"
    read input
    echo ""
    echo ""
    echo -e "${cyan}________________________________________________________________________________________${NC}"



    # check if sudo is used
    if [ "$(id -u)" != 0 ]; then
        echo ""
        echo ""
        echo "You need to run this script with ${bold}sudo${normal} at the beginning of the command"
        echo ""
        echo ""
        echo ""
        echo ""
        exit 1
    fi
    
    # update password
    echo ""
    echo ""
    echo "Type in a new password for the Raspberry Pi and press ${bold}ENTER${normal} on your keyboard" 
    echo "(note the cursor won't move as you type)"
    sudo passwd pi  # need to fix as user name may not always be pi.
    echo ""
    echo -e "${cyan}________________________________________________________________________________________${NC}"

    # update hostname
    echo ""
    echo ""
    echo "Type in a hostname for Robo-Tank and press ${bold}ENTER${normal} on your keyboard, this is similar to"
    echo "a domain name to access a website."
    read new_hostname

    while [ -z "$new_hostname" ]  # continue to ask for hostname until one in entered
    do
        if [ -z "$new_hostname" ]  # check if hostname is empty
        then
            echo "Hostname was blank, please try again."
            read new_hostname
        fi
    done

    sudo raspi-config nonint do_hostname $new_hostname &> /dev/null
    echo ""
    echo -e "${cyan}________________________________________________________________________________________${NC}"


    # update timezone
    echo ""
    echo ""
    echo "Press ${bold}ENTER${normal} on your keyboard to select your location from the list to set the timezone"
    read input
    sudo dpkg-reconfigure tzdata
    echo -e "${cyan}________________________________________________________________________________________${NC}"
    echo ""
    echo ""


    # # sync time
    echo "Syncing time                                    ...takes less than 1 minute"
    sudo systemctl start systemd-timesyncd &> /dev/null
    sudo systemctl enable systemd-timesyncd &> /dev/null


    echo "Updating config.txt File                        ...takes less than 1 minute"
    ################################## Edit config.txt file ##############################################
    FILE=/boot/config.org
    if [ ! -f "$FILE" ]; then
        sudo cp /boot/config.txt /boot/config.org &> /dev/null
    fi

    # # setup RTC
    # sudo modprobe rtc-ds1307
    # sudo bash
    # echo ds1307 0x68 > /sys/class/i2c-adapter/i2c-1/new_device
    # exit
    # sudo hwclock -w  # update RTC date time with NTP

    # Enable 1wire, rpi-pwm and i2c and set baudrate
    if grep -q 'i2c-bcm2708' /etc/modules; then
        echo ""
    else
        echo 'i2c-bcm2708' >> /etc/modules
    fi
    if grep -q 'i2c-dev' /etc/modules; then
        echo ""
    else
        echo 'i2c-dev' >> /etc/modules
    fi
    # if grep -q 'rtc-ds1307' /etc/modules; then
    #     echo ""
    # else
    #     echo 'rtc-ds1307' >> /etc/modules
    # fi

    # if grep -q 'fi' /etc/rc.local; then
    #     echo ""
    # else
    #     echo ""
    #     echo ds1307 0x68 > /sys/class/i2c-adapter/i2c-1/new_device
    #     sudo hwclock -s
    #     date
    # fi


    sudo sed -i 's/#dtparam=i2c_arm=on$/dtparam=i2c_arm=on\ndtparam=i2c_arm_baudrate=10000\ndtoverlay=i2c-rtc,ds1307\ndtoverlay=pwm-2chan/g' /boot/config.txt &> /dev/null
    sudo raspi-config nonint do_onewire 0 &> /dev/null  # Enable 1-wire
    sudo raspi-config nonint do_spi 1 &> /dev/null  # Disable spi



    if grep -q '#dtoverlay=w1-gpio' /boot/config.txt; then  # skip if this is already done
        echo ""
    else
        sudo sed -i 's/^dtoverlay=w1-gpio/#dtoverlay=w1-gpio/g' /boot/config.txt &> /dev/null

        # controller v3 sensor GPIO's
        echo 'dtoverlay=w1-gpio,gpiopin=4' | sudo tee -a /boot/config.txt &> /dev/null
        echo 'dtoverlay=w1-gpio,gpiopin=22' | sudo tee -a /boot/config.txt &> /dev/null
        echo '#dtoverlay=w1-gpio,gpiopin=14' | sudo tee -a /boot/config.txt &> /dev/null
        echo '#dtoverlay=w1-gpio,gpiopin=15' | sudo tee -a /boot/config.txt &> /dev/null
        echo '#dtoverlay=w1-gpio,gpiopin=17' | sudo tee -a /boot/config.txt &> /dev/null
        echo '#dtoverlay=w1-gpio,gpiopin=18' | sudo tee -a /boot/config.txt &> /dev/null
        echo '#dtoverlay=w1-gpio,gpiopin=27' | sudo tee -a /boot/config.txt &> /dev/null
        echo '#dtoverlay=w1-gpio,gpiopin=23' | sudo tee -a /boot/config.txt &> /dev/null
    fi

    sudo apt -y remove fake-hwclock &> /dev/null  #remove fake hardware clock
    sudo update-rc.d -f fake-hwclock remove &> /dev/null  #remove fake hardware clock

    # comment out file so DS1307 RTC can be used
    if grep -q '#if\ \[ -e /run/systemd/system' /lib/udev/hwclock-set; then  # skip if this is already done
        echo ""
    else
        sudo sed -i "s+if\ \[ -e /run/systemd/system+#if\ \[ -e /run/systemd/system+g" /lib/udev/hwclock-set &> /dev/null
        sudo sed -i '0,/    exit/{s/    exit/#    exit/}' /lib/udev/hwclock-set &> /dev/null
        sudo sed -i '0,/fi/{s/fi/#fi/}' /lib/udev/hwclock-set &> /dev/null
    fi

    # if grep -q 'dtoverlay=i2c-rtc,ds1307' /boot/config.txt; then  # skip if this is already done
    #     echo ""
    # else
    #     sudo sed -i 's/dtparam=i2c_arm_baudrate=10000$/dtparam=i2c_arm_baudrate=10000\ndtoverlay=i2c-rtc,ds1307/g' /boot/config.txt &> /dev/null
    # fi




    # echo "Updating Raspberry Pi Operating System    ...takes 1-20 minutes"
    # sudo apt update
    # sudo apt full-upgrade -y
    # sudo apt autoremove -y

    # update Raspbian
    echo "Updating Raspberry Pi Operating System          ...takes 1-30 minutes"
    apt update &> /dev/null && apt full-upgrade -y &> /dev/null && apt autoremove -y &> /dev/null && apt install -y i2c-tools &> /dev/null & PID=$!
    # While process is running...
    while kill -0 $PID 2> /dev/null; do
    printf "\e[1;33m▓"
    sleep 10
    done
    echo ""
    # printf "\e[0;37m"
    printf "\e[0;37m"


    # echo 'Installing i2c-tools                      ...takes less than 1 minute'
    # sudo apt-get install -y i2c-tools

    echo "${normal}Installing PHPMyAdmin                           ...takes about 2 minute"
    
    echo "mysql-server mysql-server/root_password password robotank" | sudo debconf-set-selections
    echo "mysql-server mysql-server/root_password_again password robotank" | sudo debconf-set-selections
    echo 'phpmyadmin phpmyadmin/dbconfig-install boolean false' | sudo debconf-set-selections
    echo 'phpmyadmin phpmyadmin/app-password-confirm password robotank' | sudo debconf-set-selections
    echo 'phpmyadmin phpmyadmin/mysql/admin-pass password robotank' | sudo debconf-set-selections
    echo 'phpmyadmin phpmyadmin/mysql/app-pass password robotank' | sudo debconf-set-selections
    echo 'phpmyadmin phpmyadmin/reconfigure-webserver multiselect apache2' | sudo debconf-set-selections

    sudo apt-get -y install phpmyadmin php-mbstring &> /dev/null & PID=$!
    # While process is running...
    while kill -0 $PID 2> /dev/null; do
    printf "\e[1;33m▓"
    sleep 5
    done
    echo ""
    printf "\e[0;37m"

    # sudo apt-get -y install phpmyadmin php-mbstring php-gettext



    # sudo apt-get -y install phpmyadmin 


    echo "${normal}Installing Apache2                              ...takes about 1 minute" 
    sudo apt-get install apache2 -y &> /dev/null & PID=$!
    # While process is running...
    while kill -0 $PID 2> /dev/null; do
    printf "\e[1;33m▓"
    sleep 5
    done
    echo ""
    printf "\e[0;37m"

    sudo systemctl restart apache2 &> /dev/null
    # sudo a2enmod rewrite
    # sudo systemctl restart apache2
    sudo chown -R pi:www-data /var/www/html/ &> /dev/null
    sudo chmod -R 770 /var/www/html/ &> /dev/null
    sudo systemctl restart apache2 &> /dev/null

    #copy updated apache2.cong file
    sudo cp /boot/robotank/install/apache2.conf /etc/apache2/apache2.conf &> /dev/null

    # wget -c https://www.robo-tank.ca/app/customRules.js

    # sudo cp customRules.js /var/www/html/js/customRules.js

    # sudo systemctl restart apache2
    
    #copy updated 99-com.rules file
    sudo cp /boot/robotank/install/99-com.rules /etc/udev/rules.d/99-com.rules &> /dev/null


    echo "${normal}Integrate PHP with Apache                       ...takes about 1 minute"
    sudo apt-get install php libapache2-mod-php -y &> /dev/null & PID=$!
    # While process is running...
    while kill -0 $PID 2> /dev/null; do
    printf "\e[1;33m▓"
    sleep 3
    done
    echo ""
    printf "\e[0;37m"
    sudo systemctl restart apache2 &> /dev/null
    sudo rm /var/www/html/index.html &> /dev/null
    
    # create test PHP file
    # echo "<?php phpinfo ();?>" > /var/www/html/index.php


    echo "${normal}Installing MySQL Database                       ...takes about 2 minute"
    sudo apt-get install mariadb-server php-mysql -y &> /dev/null & PID=$!
    # While process is running...
    while kill -0 $PID 2> /dev/null; do
    printf "\e[1;33m▓"
    sleep 3
    done
    echo ""
    printf "\e[0;37m"
    
    # sudo /usr/share/debconf/fix_db.pl  # run database fix as recommended
    sudo mysql --user=root < /boot/robotank/install/create_database.sql &> /dev/null  # create database user


    # echo "Installing PHPMyAdmin                     ...takes about 2 minute"

    # sudo apt-get -y install phpmyadmin 
    # sudo phpenmod mysqli
    # sudo /etc/init.d/apache2 restart
    # # sudo rm /var/www/html/index.php /dev/null
    # sudo mysql --user=root < /boot/robotank/install/create_database.sql  # create database user
    # sudo /etc/init.d/apache2 restart

    # update phpmyadmin, fixes error on import and export tabs
    # sudo sed -i '/if ($options != null && count($options) > 0)/c\if (! is_null($options) && count((array)$options) > 0) {' /usr/share/phpmyadmin/libraries/plugin_interface.lib.php

    
    echo "${normal}Installing Robo-Tank                            ...takes less than 1 minute"
    # sudo cp -r /boot/robotank/* /var/www/html &> /dev/null
    # sudo chown -R pi:www-data /var/www/html/ &> /dev/null
    
    
    # echo "Installing Robo-Tank Database                   ...takes less than 1 minute"
    sudo cp -r /boot/robotank/* /var/www/html &> /dev/null && sudo chown -R pi:www-data /var/www/html/ &> /dev/null && sudo mysql --user=root --password=robotank < /boot/robotank/install/robotank_database.sql &> /dev/null & PID=$!
    # While process is running...
    while kill -0 $PID 2> /dev/null; do
    printf "\e[1;33m▓"
    sleep 3
    done
    echo ""
    printf "\e[0;37m"

    # fix bug in phpmyadmin
    sudo cp /boot/robotank/install/sql.lib.php /usr/share/phpmyadmin/libraries/sql.lib.php &> /dev/null


    echo "${normal}Installing JSON Library                         ...takes less than 1 minute"
    sudo apt-get install jq -y &> /dev/null & PID=$!
    # While process is running...
    while kill -0 $PID 2> /dev/null; do
    printf "\e[1;33m▓"
    sleep 2
    done
    echo ""
    printf "\e[0;37m"


    # copy updated one wire configuration file so ds18b20 is found quicker
    sudo cp /boot/robotank/install/w1.conf /etc/modprobe.d/w1.conf &> /dev/null
    sudo cp /boot/robotank/install/modules.conf /etc/modules.conf &> /dev/null


    # copy updated php.ini file, set session to 86400 seconds and cache to 60 seconds.
    sudo cp /boot/robotank/install/php.ini /etc/php/7.3/apache2/php.ini &> /dev/null
    sudo cp /boot/robotank/install/php.ini /etc/php/7.4/apache2/php.ini &> /dev/null


    echo "${normal}Installing MySQL Library                        ...takes less than 1 minute"
    sudo apt-get install libmariadb-dev-compat libmariadb-dev -y &> /dev/null & PID=$!
    # While process is running...
    while kill -0 $PID 2> /dev/null; do
    printf "\e[1;33m▓"
    sleep 2
    done
    echo ""
    printf "\e[0;37m"


    # echo "Enabling CGI processing in apache"
    sudo systemctl restart apache2 &> /dev/null
    sudo a2enmod cgi &> /dev/null


    # echo "Enabling .htaccess headers"
    sudo systemctl restart apache2 &> /dev/null
    sudo a2enmod headers &> /dev/null


    # # enable .htaccess ExpiresActive
    sudo systemctl restart apache2 &> /dev/null
    sudo a2enmod expires &> /dev/null
    sudo systemctl restart apache2 &> /dev/null


    # echo "${normal}Installing wiringPi Library                     ...takes less than 1 minute"
    # # wget -q https://project-downloads.drogon.net/wiringpi-latest.deb
    # sudo dpkg -i /boot/robotank/install/wiring-pi/wiringpi-latest.deb &> /dev/null & PID=$!
    # # While process is running...
    # while kill -0 $PID 2> /dev/null; do
    # printf "\e[1;33m▓"
    # sleep 2
    # done
    # echo ""
    # printf "\e[0;37m"


    echo "${normal}Installing libwebsockets Library                ...takes less than 1 minute"
    sudo apt-get install libwebsockets-dev -y &> /dev/null & PID=$!
    # While process is running...
    while kill -0 $PID 2> /dev/null; do
    printf "\e[1;33m▓"
    sleep 2
    done
    echo ""
    printf "\e[0;37m"


    # echo "${normal}Installing JsonCpp Library                      ...takes less than 1 minute"
    # sudo apt-get install libjsoncpp-dev -y &> /dev/null & PID=$!
    # # While process is running...
    # while kill -0 $PID 2> /dev/null; do
    # printf "\e[1;33m▓"
    # sleep 2
    # done
    # echo ""
    # printf "\e[0;37m"


    echo "${normal}Installing libcurl Library                      ...takes less than 1 minute"
    sudo apt-get install libcurl4-openssl-dev -y &> /dev/null & PID=$!
    # While process is running...
    while kill -0 $PID 2> /dev/null; do
    printf "\e[1;33m▓"
    sleep 2
    done
    echo ""
    printf "\e[0;37m"


    echo "${normal}Installing libquickmail Library                 ...takes about 1 minute"
    # cd /boot/robotank/install/libquickmail/ &> /dev/null  # change directory
    # sudo ./configure &> /dev/null && sudo make &> /dev/null && sudo make install &> /dev/null && sudo sh -c "echo '/usr/local/lib' >> /etc/ld.so.conf" &> /dev/null && sudo ldconfig &> /dev/null & PID=$!
    # # While process is running...
    # while kill -0 $PID 2> /dev/null; do
    # printf "\e[1;33m▓"
    # sleep 4
    # done
    # echo ""
    # printf "\e[0;37m"

    sudo cp /boot/robotank/install/libquickmail/libquickmail.a /usr/lib &> /dev/null
    sudo cp /boot/robotank/install/libquickmail/libquickmail.la /usr/lib &> /dev/null
    sudo cp /boot/robotank/install/libquickmail/libquickmail.so /usr/lib &> /dev/null
    sudo cp /boot/robotank/install/libquickmail/libquickmail.so.0 /usr/lib &> /dev/null
    sudo cp /boot/robotank/install/libquickmail/libquickmail.so.0.0.0 /usr/lib &> /dev/null
    sudo cp /boot/robotank/install/libquickmail/libquickmaillight.a /usr/lib &> /dev/null
    sudo cp /boot/robotank/install/libquickmail/libquickmaillight.la /usr/lib &> /dev/null
    sudo cp /boot/robotank/install/libquickmail/libquickmaillight.so /usr/lib &> /dev/null
    sudo cp /boot/robotank/install/libquickmail/libquickmaillight.so.0 /usr/lib &> /dev/null
    sudo cp /boot/robotank/install/libquickmail/libquickmaillight.so.0.0.0 /usr/lib &> /dev/null
    sudo cp /boot/robotank/install/libquickmail/quickmail.h /usr/local/include &> /dev/null
    sudo sh -c "echo '/usr/local/lib' >> /etc/ld.so.conf" &> /dev/null
    # sudo ldconfig




    # echo "${normal}Installing libgpiod ABI Library                 ...takes about 1 minute"
    # sudo apt install gpiod -y &> /dev/null && sudo apt install libgpiod-dev -y &> /dev/null & PID=$!
    # # While process is running...
    # while kill -0 $PID 2> /dev/null; do
    # printf "\e[1;33m▓"
    # sleep 4
    # done
    # echo ""
    # printf "\e[0;37m"



    # echo "Installing libquickmail Library                 ...takes about 1 minute"
    # cd /boot/robotank/install/libquickmail/ &> /dev/null  # change directory
    # sudo ./configure &> /dev/null  # configure libquickmail
    # sudo make &> /dev/null  # compile libquickmail
    # sudo make install &> /dev/null  # install libquickmail
    # sudo sh -c "echo '/usr/local/lib' >> /etc/ld.so.conf" &> /dev/null  # add path to installed 3rd party libraries
    # sudo ldconfig &> /dev/null  # refresh cache
    # # sudo cp /boot/robotank/install/libquickmail/quickmail.h /usr/local/include/  # MAYBE
    
    
    # update Raspbian
    echo "${normal}Updating Raspberry Pi Operating System          ...takes 1-30 minutes"
    apt update &> /dev/null && apt full-upgrade -y &> /dev/null && apt autoremove -y &> /dev/null & PID=$!
    # While process is running...
    while kill -0 $PID 2> /dev/null; do
    printf "\e[1;33m▓"
    sleep 10
    done
    echo ""
    # printf "\e[0;37m"
    printf "\e[0;37m"


    echo "${normal}Installing Robo-Tank Service on Pi              ...takes less than 1 minute"
    sudo cp /boot/robotank/install/robotank.service /etc/systemd/system/robotank.service &> /dev/null

    # give Robo-Tank service file permission
    sudo chmod -R 770 /etc/systemd/system/robotank.service &> /dev/null

    # enable Robo-Tank service to run at startup
    sudo systemctl enable robotank.service &> /dev/null
    sudo systemctl start robotank.service &> /dev/null
    # sudo systemctl stop robotank.service
    # sudo systemctl disable robotank.service
    
    echo "Removing Robo-Tank Installation Files           ...takes less than 1 minute"
    sudo rm -r /boot/robotank/ &> /dev/null
    sudo rm -r "Robo-Tank_v6_5.zip" &> /dev/null

    echo ""
    echo -e "${cyan}________________________________________________________________________________________${NC}"
    echo ""
    echo ""
    echo ""
    echo ""
    echo ""
    echo "You have successfully installed Robo-Tank, you can now press ${bold}ENTER${normal}"
    echo "on your keyboard to restart your Raspberry Pi."
    echo ""
    echo "After the Raspberry Pi restarts open a web browser from any device on your local "
    echo "network and type one of the links below. The first link is the IP address of the"
    echo "Raspberry Pi, the 2nd link is the hostname you added during the installation. Write"
    echo "these down or create a bookmark in your browser. Note it is possible your network"
    echo "changes the IP address for the Raspberry Pi and the link no longer works, this is"
    echo "why we setup a hostname as this will never change."
    echo ""
    ip= hostname -I | awk '{ print "http://" $1 }'
    echo "${bold}http://$new_hostname${normal}"
    echo ""
    echo ""

    echo "The default login for Robo-Tank is as follows."
    echo ""
    echo "Username = ${bold}Robo-Tank${normal}"
    echo "Password = ${bold}Robo-Tank${normal}"
    echo ""
    echo ""
    echo "Have a great day!"
    echo ""
    echo ""
    echo ""
    echo "Press ${bold}ENTER${normal} on your keyboard to restart the Raspberry Pi."
    echo ""
    echo ""
    echo ""
    read input
    

    echo "Expanding file system                           ...takes less than 1 minute"
    # # # expand file system
    sudo raspi-config --expand-rootfs &> /dev/null

    sudo reboot
# fi
