#!/bin/bash
WEBIDE_ROOT="/usr/share/adafruit/webide"
#needed for SSH key and config access at this point.
WEBIDE_HOME="/home/webide"

echo "**** Create webide user and group ****"
groupadd webide || true
useradd -g webide webide || true
usermod -a -G i2c,sudo webide || true

chown -R webide:webide "$WEBIDE_HOME"
chown -R webide:webide "$WEBIDE_ROOT"

echo 'webide "node" "service adafruit-webide.sh restart" ""' >> /etc/restartd.conf

cd /etc/init.d

NODE_PATH=""
ARCH=$(dpkg --print-architecture)
if [ $ARCH = armhf ]; then
  NODE_PATH="\/usr\/share\/adafruit\/webide\/bin\/node_hf\/node"
  chmod +x "$WEBIDE_ROOT/bin/node_hf/node"
else
  NODE_PATH="\/usr\/share\/adafruit\/webide\/bin\/node_sf\/node"
  chmod +x "$WEBIDE_ROOT/bin/node_sf/node"
fi
sed -i "s/NODE_PATH/$NODE_PATH/g" adafruit-webide.sh

update-rc.d adafruit-webide.sh defaults

echo "Attempting to force reload date and time from ntp server"
/etc/init.d/ntp force-reload

#Check if port 80 is in use, use 3000 if so.
PORT_USED=""
if netstat -lnt | awk '$6 == "LISTEN" && $4 ~ ".80"' | grep -q "LISTEN"
then
  redis-cli HMSET server port 8080
  PORT_USED=":8080"
  echo "**** WARNING: PORT 80 IN USE. FALLING BACK TO 8080. ****"
  echo "**** TO CHOOSE A DIFFERENT PORT USE THE FOLLOWING COMMAND: ****"
  echo "**** redis-cli HMSET server port 8080 ****"
  echo "**** AND RESTART THE SERVER ****"
fi

service adafruit-webide.sh start

#kill all restartd processes, and restart one
pkill -f restartd || true
sleep 5s
restartd


echo "**** Starting the server...(please wait) ****"
sleep 20s

echo "**** The Adafruit WebIDE is installed and running! ****"
echo "**** Commands: sudo service adafruit-webide.sh {start,stop,restart} ****"
echo "**** Navigate to http://$(hostname).local$PORT_USED to use the WebIDE"

exit 0