#!/bin/bash
#
# Copyright 2016,2017 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
if [ "$EUID" == "0" ]
  then echo -en "\nRoot user detected. Typically install as a normal user. No need for sudo.\r\n"
  read -p "Are you really sure you want to install as root ? (y/N) ? " yn
  case $yn in
    [Yy]* )
    ;;
    * )
      exit
    ;;
  esac
fi
if [[ "$(uname)" != "Darwin" ]]; then
if [[ $(cat /etc/*-release | grep VERSION=) != *"wheezy"* ]]; then
echo -e '\033]2;'Node-RED update'\007'
echo " "
echo "This script will remove any pre-installed versions of node.js and Node-RED"
echo "and replace them with node.js 6.x LTS (boron) and the latest Node-RED from Npm."
echo "To do this it runs commands as root - please satisfy yourself that this will"
echo "not damage your Pi, or otherwise compromise your configuration."
echo " "
echo "Doing this may also be 'a bad thing' if you have installed lots of extra nodes."
echo "Especially if they have any native binary component. Some nodes in your"
echo "~/.node-red directory will probably need to be re-installed afterwards, some"
echo "may need you to run npm update, and some may require you to run npm rebuild."
echo " "
read -p "Are you really sure you want to do this ? (y/N) ? " yn
case $yn in
    [Yy]* )
        # this script assumes that $HOME is the folder of the user that runs node-red
        # that $USER is the user name and the group name to use when running is the
        # primary group of that user
        # if this is not correct then edit the lines below
        NODERED_HOME=$HOME
        NODERED_USER=$USER
        NODERED_GROUP=`id -gn`
        TICK='\033[1;32m\u2714\033[0m'
        CROSS='\033[1;31m\u2718\033[0m'
        cd "$NODERED_HOME" || exit 1
        clear
        echo "Running for user $USER at $HOME"
        time1=$(date)
        echo "\n\n***********************************" | sudo tee -a /var/log/nodered-install.log >>/dev/null
        echo "Started : "$time1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        echo "Running for user $USER at $HOME" | sudo tee -a /var/log/nodered-install.log >>/dev/null
        echo -ne '\r\nThis can take 20-30 minutes on a Pi 1 - please wait.\r\n\n'
        echo -ne '  Stop Node-RED                       \r\n'
        echo -ne '  Remove old version of Node-RED      \r\n'
        echo -ne '  Remove old version of node.js       \r\n'
        echo -ne '  Install node.js                     \r\n'
        echo -ne '  Clean npm cache                     \r\n'
        echo -ne '  Install Node-RED core               \r\n'
        echo -ne '  Install extra nodes                 \r\n'
        echo -ne '  Install serialport node             \r\n'
        echo -ne '  Npm rebuild existing nodes          \r\n'
        echo -ne '  Add menu shortcut                   \r\n'
        echo -ne '  Update systemd script               \r\n'
        echo -ne '  Update update script                \r\n'
        echo -ne '\r\nAny errors will be logged to   /var/log/nodered-install.log\r\n'
        echo -ne '\033[14A'

        # stop any running node-red service
        if sudo service nodered stop 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null ; then CHAR=$TICK; else CHAR=$CROSS; fi
        echo -ne "  Stop Node-RED                       $CHAR\r\n"

        # remove any old node-red installs or files
        sudo apt-get remove -y nodered 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        sudo rm -rf /usr/local/lib/node_modules/node-red* /usr/local/bin/node-red* 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        sudo rm -rf /usr/lib/node_modules/node-red* /usr/bin/node-red* 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        echo -ne '  Remove old version of Node-RED      \033[1;32m\u2714\033[0m\r\n'

        # maybe remove node.js - or upgrade if nodesoure.list exists
        if [[ -e $NODERED_HOME/.nvm ]]; then
            echo -ne '  Using NVM to manage node.js         +   please run   \033[0;36mnvm use lts/*\033[0m\r\n'
            export NVM_DIR=$NODERED_HOME/.nvm
            [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
            nvm install lts/* >/dev/null 2>&1
            nvm use lts/* >/dev/null 2>&1
            nvm alias default lts/* >/dev/null 2>&1
            echo -ne "  Update node.js LTS                  $CHAR"
        elif [[ $(which n) ]]; then
            echo -ne "  Using N to manage node.js           +\r\n"
            if sudo n lts 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null; then CHAR=$TICK; else CHAR=$CROSS; fi
            echo -ne "  Update node.js LTS                  $CHAR"
        elif [ -e /etc/apt/sources.list.d/nodesource.list ]; then
            nv=`node -v | cut -d "." -f1`
            if [ "$nv" = "v0" ] || [ "$nv" = "v1" ] || [ "$nv" = "v3" ] || [ "$nv" = "v4" ] || [ "$nv" = "v5" ]; then
                sudo rm -rf /etc/apt/sources.d/nodesource.list
                if curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash - 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null; then CHAR=$TICK; else CHAR=$CROSS; fi
            else
                CHAR="-"
            fi
            echo -ne "  Remove old version of node.js       $CHAR\r\n"
            echo -ne "  Update node.js LTS                  \r"
            if sudo apt-get install -y nodejs 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null; then CHAR=$TICK; else CHAR=$CROSS; fi
            echo -ne "  Update node.js LTS                  $CHAR"
        else
            # clean out old nodejs stuff
            sudo apt-get remove -y nodejs nodejs-legacy npm 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
            sudo dpkg -r nodejs 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
            sudo dpkg -r node 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
            sudo rm -rf /usr/local/bin/npm* 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
            sudo apt-get autoremove -y 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
            echo -ne "  Remove old version of node.js       \033[1;32m\u2714\033[0m\r\n"
            # grab the correct LTS bundle for the processor
            if cat /proc/cpuinfo | grep model | grep -q ARMv6 ; then
                echo -ne "  Install node.js for Armv6           \r"
                f=$(curl -sL https://nodejs.org/download/release/latest-boron/ | grep "armv6l.tar.gz" | cut -d '"' -f 2)
                curl -sL -o node.tgz https://nodejs.org/download/release/latest-boron/$f 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
                # unpack it into the correct places
                if sudo tar -zxf node.tgz --strip-components=1 -C /usr 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null; then CHAR=$TICK; else CHAR=$CROSS; fi
                # remove the tgz file to save space
                rm node.tgz 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
                echo -ne "  Install node.js for Armv6           $CHAR"
            else
                echo -ne "  Install node.js LTS                 \r"
                # use the official script to install for other debian platforms
                curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash - 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
                if sudo apt-get install -y nodejs 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null; then CHAR=$TICK; else CHAR=$CROSS; fi
                echo -ne "  Install node.js LTS                 $CHAR"
            fi
        fi
        hash -r
        rc=""
        if nov=$(node -v 2>/dev/null); then :; else rc="ERR"; fi
        if npv=$(npm -v 2>/dev/null); then :; else rc="ERR"; fi
        if [[ $rc == "" ]]; then
            echo -ne "   Node $nov   Npm $npv\r\n"
        else
            echo -ne "\b$CROSS   Failed to install node.js - Exit\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
            exit 2
        fi

        # clean up the npm cache and node-gyp
        sudo npm cache clean --force 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        if sudo rm -rf "$NODERED_HOME/.node-gyp" "$NODERED_HOME/.npm" /root/.node-gyp /root/.npm; then CHAR=$TICK; else CHAR=$CROSS; fi
        echo -ne "  Clean npm cache                     $CHAR\r\n"

        # and install Node-RED
        if sudo npm i -g --unsafe-perm --no-progress node-red 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null; then CHAR=$TICK; else CHAR=$CROSS; fi
        nrv=$(npm --no-progress -g ls node-red | grep node-red | cut -d '@' -f 2 | sudo tee -a /var/log/nodered-install.log) >>/dev/null 2>&1
        echo -ne "  Install Node-RED core               $CHAR   $nrv\r\n"

        # install extra nodes - random, ping, smooth, iot, play-audio
        if sudo npm i -g --unsafe-perm --no-progress node-red-node-random node-red-node-ping node-red-node-smooth node-red-contrib-ibm-watson-iot node-red-contrib-play-audio 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null; then CHAR=$TICK; else CHAR=$CROSS; fi
        # install Pi nodes (and remove GPIO if not on Pi)
        if sudo grep -q BCM2 /proc/cpuinfo; then
            sudo npm i -g --unsafe-perm --no-progress node-red-node-ledborg node-red-node-pi-sense-hat 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        else
            sudo rm -rf /usr/lib/node_modules/node-red/nodes/core/hardware/36*
        fi
        echo -ne "  Install extra nodes                 $CHAR\r\n"

        # remove and re-install serialport (won't need to on/after 0.16)
        sudo rm -rf /usr/lib/node_modules/node-red/node_modules/node-red-node-serialport
        if sudo npm i -g --unsafe-perm --no-progress node-red-node-serialport 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null; then CHAR=$TICK; else CHAR=$CROSS; fi
        echo -ne "  Install serialport node             $CHAR\r\n"

        # try to rebuild any already installed nodes
        if [ -d "$NODERED_HOME/.node-red" ]; then
            pushd "$NODERED_HOME/.node-red" 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
            if [ -e "node_modules/node-red-node-serialport" ]; then rm -rf node_modules/node-red-node-serialport; fi
            if npm rebuild  2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null; then CHAR=$TICK; else CHAR=$CROSS; fi
            popd 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        fi
        echo -ne "  Npm rebuild existing nodes          $CHAR\r\n"

        # add the shortcut and start/stop/log scripts to the menu
        sudo curl -sL -o /usr/share/icons/gnome/scalable/apps/node-red-icon.svg https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/node-red-icon.svg 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        sudo curl -sL -o /usr/share/applications/Node-RED.desktop https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/Node-RED.desktop 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        sudo curl -sL -o /usr/bin/node-red-start https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/node-red-start2 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        sudo curl -sL -o /usr/bin/node-red-stop https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/node-red-stop 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        sudo curl -sL -o /usr/bin/node-red-log https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/node-red-log 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        sudo chmod +x /usr/bin/node-red-st*
        sudo chmod +x /usr/bin/node-red-log
        echo -ne "  Add menu shortcut                   \033[1;32m\u2714\033[0m\r\n"

        # add systemd script and configure it for $USER
        if sudo curl -sL -o /lib/systemd/system/nodered.service https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/nodered.service 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null; then CHAR=$TICK; else CHAR=$CROSS; fi
        # set the User Group and WorkingDirectory in nodered.service
        sudo sed -i 's#^User=pi#User='$NODERED_USER'#;s#^Group=pi#Group='$NODERED_GROUP'#;s#^WorkingDirectory=/home/pi#WorkingDirectory='$NODERED_HOME'#;' /lib/systemd/system/nodered.service
        sudo systemctl daemon-reload 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        echo -ne "  Update systemd script               $CHAR\r\n"

        # on Pi, add cpu temp example, make sure ping works, refresh desktop menu
        if sudo grep -q BCM270 /proc/cpuinfo; then
            lxpanelctl restart 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
            sudo curl -sL -o /usr/lib/node_modules/node-red-contrib-ibm-watson-iot/examples/Pi\ cpu\ temperature.json https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/Pi%20cpu%20temperature.json 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
            sudo setcap cap_net_raw+eip $(eval readlink -f `which node`) 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
            sudo setcap cap_net_raw=ep /bin/ping 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
            sudo setcap cap_net_raw=ep /bin/ping6 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
        fi

        # Finally update the update script
        if sudo curl -sL -o /tmp/update-nodejs-and-nodered https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/update-nodejs-and-nodered 2>&1 | sudo tee -a /var/log/nodered-install.log >>/dev/null; then CHAR=$TICK; else CHAR=$CROSS; fi
        sudo chmod +x /tmp/update-nodejs-and-nodered
        echo -ne "  Update update script                $CHAR\r\n"

        echo -ne "\r\n\r\n\r\n"
        echo -ne "All done.\r\n"
        echo -ne "  You can now start Node-RED with the command  \033[0;36mnode-red-start\033[0m\r\n"
        echo -ne "  or using the icon under   Menu / Programming / Node-RED\r\n"
        echo -ne "  Then point your browser to \033[0;36mlocalhost:1880\033[0m or \033[0;36mhttp://{your_pi_ip-address}:1880\033[0m\r\n"
        echo -ne "\r\nStarted  $time1  -  Finished  $(date)\r\n\r\n"
        echo "Finished : "$time1 | sudo tee -a /var/log/nodered-install.log >>/dev/null
    ;;
    * )
        echo " "
        exit 1
    ;;
esac
else
echo " "
echo "Sorry - I'm not able to upgrade old Wheezy installations. Please think about updating."
echo "Please see the documentation at http://nodered.org/docs/getting-started/upgrading."
echo " "
exit 1
fi
else
echo " "
echo "Sorry - I'm not supposed to be run on a Mac."
echo "Please see the documentation at http://nodered.org/docs/getting-started/upgrading."
echo " "
exit 1
fi
if [ -e /tmp/update-nodejs-and-nodered ] && [ -s /tmp/update-nodejs-and-nodered ]; then sudo mv /tmp/update-nodejs-and-nodered /usr/bin/update-nodejs-and-nodered; fi
