#!/bin/bash

key_32=$(openssl rand -hex 32)
key_64=$(openssl rand -hex 64)
hostname=$(hostname)

node_red(){
echo "Start installing node-red, which first will install dependencies on nodejs, npm"
apt update &> /dev/null;
echo  "-----------------------------------------------------------------------"
	if [[ ! -f /usr/bin/nodejs ]]; then
		apt install nodejs -y &> /dev/null;
		[[ -f /usr/bin/nodejs ]] && echo "nodejs install successfully"
		if [[ ! -f /usr/bin/nodejs ]]; then
			echo "nodejs installation failed, please try again" && exit
			echo  "-----------------------------------------------------------------------"
		fi
	fi

echo  "-----------------------------------------------------------------------"
	if [[ ! -f /usr/bin/npm ]]; then
		apt install npm -y  &> /dev/null;
		[[  -f /usr/bin/npm ]] && echo "npm install successfully"
		if [[ ! -f /usr/bin/npm ]]; then
			echo "npm installation failed, please try again" && exit
			echo  "-----------------------------------------------------------------------"
		fi
	fi

echo  "-----------------------------------------------------------------------"
	if [[ !  -f /usr/local/bin/node-red ]]; then
		npm install -g --unsafe-perm node-red  &> /dev/null;
		[[ -f /usr/local/bin/node-red ]] &&  echo "node-red install successfully" && nodered=1
		if [[ ! -f /usr/local/bin/node-red ]]; then
			echo "node-red installation failed, please try again" && exit
			echo  "-----------------------------------------------------------------------"
		fi
	fi
	
	if [[  -f /usr/local/bin/node-red ]]; then
		[[ ! -f /lib/systemd/system/nodered.service ]] && wget http://repo.dragino.com/release/tool/nodered/nodered.service -P /lib/systemd/system/ &> /dev/null 
		if [[ -f /lib/systemd/system/nodered.service ]]; then
			echo "-----------------------------------------------------------------------"
			systemctl start nodered;
			echo "Start the Nodr-red process"
			echo "Then point your browser to your_hots_IPv4_address:1880 or http://$hostname:1880"
			echo
			echo "Some helpful commands for node-red:"
			echo
			echo start:
			echo    "$ systemctl start nodered"
			echo
			echo stop:
			echo    "$ systemctl stop nodered"
			echo
			echo restart:
			echo    "$ systemctl restart nodered"
			echo
			echo Boot start
			echo	"$ systemctl enable nodered"
			echo "-----------------------------------------------------------------------"
		fi
	fi

}




case "$1" in
        node-red)
		node_red
                ;;
        *)
esac

exit