cd /home/pi
cd $HOME
sudo apt-get update
sudo apt-get remove node nodejs nodejs-legacy -y
#sudo apt-get install node nodejs nodejs-legacy -y
sudo apt-get install git git-core libnss-mdns libavahi-compat-libdnssd-dev -y
#sudo sh -c "curl https://www.npmjs.com/install.sh | sh"
if uname -m | grep -q "armv6l"; then
    clear
    echo "legacy Raspberry Pi detected"
    sleep 1
    sudo wget http://node-arm.herokuapp.com/node_latest_armhf.deb
    sudo dpkg -i node_latest_armhf.deb
    sudo rm -rf node_latest_armhf.deb
    sudo npm install -g n
    sudo rm /usr/local/bin/node
    sudo rm -rf /usr/local/lib/node_modules/npm
    sudo n prune
    sudo n 8.2.1
else
    sudo curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
    sudo apt-get install nodejs -y
    sudo npm install -g n
    sudo rm /usr/local/bin/node
    sudo rm -rf /usr/local/lib/node_modules/npm
    sudo n prune
    sudo n 8.2.1
fi
sudo apt-get install gcc g++ make -y
sudo apt-get install -y nodejs
#sudo sh -c "curl https://www.npmjs.com/install.sh | sh"
sudo npm install -g node-gyp
sudo git clone --branch v0.4.27 https://github.com/KhaosT/HAP-NodeJS.git
#sudo git clone https://github.com/KhaosT/HAP-NodeJS.git
cd HAP-NodeJS/
sudo sh -c "rm -rf accessories/AirConditioner_accessory.js"
sudo npm install
cd /home/pi/HAP-NodeJS/lib
sudo sh -c "mv Camera.js OriginalCamera.bak"
sudo sh -c "wget https://sumju.net/Camera.js -O Camera.js"
sudo sh -c "echo '[Unit]
Description=HAP-NodeJS Server
After=syslog.target network-online.target

[Service]
Type=simple
User=root
ExecStart=/usr/bin/node /home/pi/HAP-NodeJS/CameraCore.js
Restart=on-abort

[Install]
WantedBy=multi-user.target' > /etc/systemd/system/hap-nodejs.service"
sudo sh -c "echo 'gpu_mem=256' >> /boot/config.txt"
sudo sh -c "systemctl enable hap-nodejs.service"
sudo sh -c "systemctl start hap-nodejs.service"
