#!/bin/bash

set -eE
trap 'echo "An error occurred on line ${LINENO}"' ERR

echo ' '
echo 'Installer of REXYGEN runtime components'
echo ' for Raspberry Pi with PiFace Digital  '
echo '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
echo ' '

ROOT=$(dirname $(readlink -f $0))

if [ "$EUID" -ne 0 ]
  then echo "Please run this script as root"
  exit
fi

# Install core modules

REPO=debian-rex-2.50
CHANNEL=stable

# Parse arguments
while test $# -gt 0
do
    case "$1" in
        --stable)
            ;;
        --testing)
            REPO=debian-rex-2.50-testing
            CHANNEL=stable
            ;;
        --next)
            REPO=debian-rex-2.50-next
            CHANNEL=next
            ;;
        *)
            echo "Error: unsupported argument $1"
            exit 1
            ;;
    esac
    shift
done

# Checking Raspbian distribution...

if cat /etc/*-release | grep VERSION= | grep -iq Wheezy; then
  echo "Raspbian Wheezy not supported, please upgrade your system..."
  exit 9
elif cat /etc/*-release | grep VERSION= | grep -iq Jessie; then
  echo "Raspbian Jessie not supported, please upgrade your system..."
  exit 9
elif cat /etc/*-release | grep VERSION= | grep -iq Stretch; then
  DISTRO="Stretch"
  DISTDIR="stretch"
elif cat /etc/*-release | grep VERSION= | grep -iq Buster; then
  DISTRO="Buster"
  DISTDIR="buster"
else
  DISTRO="Bullseye"
  DISTDIR="bullseye"
fi
echo "Raspbian $DISTRO detected..."

echo " "
echo "This installation script may be used only on a FRESH RASPBIAN $DISTRO IMAGE."
echo "Use at your own risk."
read -p "Is it OK to proceed? [y/N] " -n 1 -r
echo ' '
if ! [[ $REPLY =~ ^[Yy]$ ]]
then
  echo "Exiting..."
  exit 9
fi
echo ' '

echo 'Adding REX Controls key...'

curl -o /tmp/rex.pub http://download.rexcontrols.cz/files/key/rex-debian-key.pub

if [ $? -ne 0 ]
  then echo 'ERROR: Failed to download the REX Controls key! Check your Internet connection...'
  exit 9
fi

apt-key add /tmp/rex.pub

if [ $? -ne 0 ]
  then echo 'ERROR: Failed to add the REX Controls key! Try updating your Raspberry Pi.'
  exit 9
fi

echo "Adding APT source repositories for distro ${DISTRO} and channel ${CHANNEL}..."
echo "deb http://download.rexcontrols.cz/repositories/${REPO}/ ${DISTDIR} non-free" > /etc/apt/sources.list.d/rexcontrols-rex.list

apt update

### Temporary hack to overcome post-installation problems of owserver (OWFS) in Buster
set +e
if [ "$DISTRO" = "Buster" ]
then
    echo "Installation in progress, please wait..."
    apt install -y --install-recommends owserver > /dev/null 2> /dev/null
    sed -i 's/Restart=on-failure/Restart=on-failure\nRestartSec=3/' /lib/systemd/system/owserver.service
    systemctl daemon-reload
    systemctl restart owserver
    dpkg --configure -a
fi
set -e
### End of hack

echo 'Installing runtime modules of REXYGEN...' 
apt install -y --install-recommends rexygen-runtime

# REXYGEN installer
# HW specific operations - PiFace Digital

if [ "$EUID" -ne 0 ]
  then echo "Please run this script as root"
  exit
fi

#--- PiFace Digital specific operations ---
cp /boot/config.txt /boot/config.txt.rexbak
if ! grep -q '^dtparam=spi=on' /boot/config.txt
    then echo 'dtparam=spi=on' >> /boot/config.txt
fi

#--- Final reboot ---
echo ' '
echo 'Runtime modules of REXYGEN for Raspberry Pi with PiFace Digital add-on board were successfully installed.'
echo ' '
echo '!!! REBOOT IS REQUIRED !!!'
echo ' '
echo 'Afterwards you will be able to program your Raspberry Pi using REXYGEN Studio.'
echo ' '

# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
  printf "The IP address of this device is %s\n" "$_IP"
fi
echo ' '

read -p "Is it OK to reboot now? [y/N] " -n 1 -r
echo ' '
if [[ $REPLY =~ ^[Yy]$ ]]
then
    reboot
else
  echo 'Remember to reboot your Raspberry Pi at your earliest convenience.'
fi
echo ' '
