#!/bin/bash
# For Fhem installation see http://www.fhemwiki.de/wiki/Raspberry_Pi

# Navigate to install location
cd ~/Fhem

# Prepare installation.
echo Aktualisierung von Repository und Installation. 
sudo apt-get -y update 
sudo apt-get -y upgrade

echo Installation of Fhem.
sudo apt-get -y install apt-transport-https
sudo apt-get -y install perl libdevice-serialport-perl libio-socket-ssl-perl libwww-perl
rm fhem.deb

#wget http://debian.fhem.de/fhem-5.8.deb
wget http://fhem.de/fhem-5.8.deb
sudo dpkg -i -E fhem-5.8.deb
sudo apt-get install -y -f
# Save current configuration.
sudo mv /opt/fhem/fhem.cfg /opt/fhem/fhem.cfg.bak

# Copy GPIO4 modul and Hubo demo configuration and allow fhem access to i2c bus.
echo Prepare modules for usage of Hubo hardware.
sudo cp /opt/fhem/contrib/58_GPIO4.pm /opt/fhem/FHEM/58_GPIO4.pm
sudo cp ~/Fhem/bpi_fhem.cfg /opt/fhem/fhem.cfg
sudo chmod 666 /opt/fhem/fhem.cfg
sudo adduser fhem i2c

# Restart fhem in order to recognise the configuration change.
echo Restart fhem in order to recognise the configuration change.
sudo /etc/init.d/fhem stop
sudo /etc/init.d/fhem start
sudo update-rc.d fhem remove

# Rebuild Hubo library in case the wrong installer had been chosen before.
~/HuboDemo/./build

# Copying Hubo library to lib space.
sudo cp ~/HuboDemo/libhubo.so /usr/lib/libhubo.so.1
sudo chmod 755 /usr/lib/libhubo.so.1

# Create directory Automation to store executables.
sudo rm -r ~/HuboDemo/Automation/
mkdir ~/HuboDemo/Automation

# Make Hubo-Demos accessible with no sudo (not all might be reqired though)
sudo cp         ~/HuboDemo/GetAnalogInput/bpi_GetAnalogInput      ~/HuboDemo/Automation/GetAnalogInput
sudo chown root ~/HuboDemo/Automation/GetAnalogInput
sudo chmod 755  ~/HuboDemo/Automation/GetAnalogInput
sudo chmod u+s  ~/HuboDemo/Automation/GetAnalogInput

sudo cp         ~/HuboDemo/GetDigitalInput/bpi_GetDigitalInput    ~/HuboDemo/Automation/GetDigitalInput
sudo chown root ~/HuboDemo/Automation/GetDigitalInput
sudo chmod 755  ~/HuboDemo/Automation/GetDigitalInput
sudo chmod u+s  ~/HuboDemo/Automation/GetDigitalInput

sudo cp         ~/HuboDemo/SetDigitalOutput/bpi_SetDigitalOutput  ~/HuboDemo/Automation/SetDigitalOutput
sudo chown root ~/HuboDemo/Automation/SetDigitalOutput
sudo chmod 755  ~/HuboDemo/Automation/SetDigitalOutput
sudo chmod u+s  ~/HuboDemo/Automation/SetDigitalOutput

# RCSocket is currently not supported for Banana Pi.
#sudo cp         ~/HuboDemo/RCSocket/bpi_RCSocket                  ~/HuboDemo/Automation/RCSocket
#sudo chown root ~/HuboDemo/Automation/RCSocket
#sudo chmod 755  ~/HuboDemo/Automation/RCSocket
#sudo chmod u+s  ~/HuboDemo/Automation/RCSocket

echo 
echo You can now access fhem through your browser: http://bpi-iot-ros-ai:8083 
echo
echo To stop  fhem type: sudo /etc/init.d/fhem stop
echo To start fhem type: sudo /etc/init.d/fhem start
