#!/bin/bash

onerror()
{
    echo "ggRock hasn't been installed due to error. Please, try to run installation script once again. If the error persists, contact with developer."
    exit 1
}

# Exit on error
trap onerror ERR
# Catch errors in pipelines
set -o pipefail

if [[ $EUID -ne 0 ]]; then
   echo "ggRock installation script must be run as root." 
   exit 1
fi

apt-get -y update
apt-get -y dist-upgrade
apt-get -y install curl

CODENAME=$(lsb_release -c -s)
if [ "$CODENAME" == "buster" ]; then
    curl -s https://packagecloud.io/install/repositories/ggcircuit/unstable/script.deb.sh | bash
else
    curl -s https://packagecloud.io/install/repositories/ggcircuit/stable/script.deb.sh | bash
fi

apt-get -y install ggrock-linux-configurator

ggrock-linux-configurator

apt-get -y install ggrock

IP_ADDRESSES_STRING=$(hostname -I)

echo ""
echo ""
echo "ggRock has been installed. Open it in your web browser:"

IP_ADDRESSES=$(echo $IP_ADDRESSES_STRING | tr " " "\n")

for addr in $IP_ADDRESSES
do
    echo "http://$addr/"
done

echo ""
echo ""
