#!/bin/bash -e


# Current Directory
CURRENT_DIR=$(pwd)


# Header Function
function printhead() {
  clear
  echo "--------------------------------------------------"
  echo "Jitsi VideoBridge Automatic Installer"
  echo "Email: dimas.restu@student.upi.edu"
  echo "--------------------------------------------------"
  echo ""
}


# Check Privileges
if [[ $UID -ne 0 ]]; then
  echo "Administrator Privilege Needed. Please Run This Program As An Administrator/Root User!"
  exit 1
fi


# Check Platform
if [[ $(uname -i) != "x86_64" ]]; then
  echo "Platform Not Supported. Please Run This Program in 64-bit Platform!"
  exit 1
fi


# Change Working Directory
printhead
echo "--------------------------------------------------"
echo "Change Working Directory"
cd $CURRENT_DIR
echo "--------------------------------------------------"
sleep 2


# Install Dependencies and Tools
printhead
echo "--------------------------------------------------"
echo "Install Dependencies and Tools"
apt-get update && apt-get install -y apt-transport-https apt-utils ca-certificates gnupg \
  && apt-get install -y jq procps curl vim iputils-ping net-tools htop iftop iperf3
echo "--------------------------------------------------"
sleep 2


# Install OpenJDK 8 JRE
printhead
echo "--------------------------------------------------"
echo "Install OpenJDK 8 JRE"
apt-get update && apt-get install -y openjdk-8-jre-headless
update-java-alternatives --jre-headless --set java-1.8.0-openjdk-amd64
echo "--------------------------------------------------"
sleep 2


# Installing Jitsi Repository
printhead
echo "--------------------------------------------------"
echo "Installing Jitsi Repository"
wget -qO - https://download.jitsi.org/jitsi-key.gpg.key | apt-key add -
echo "deb https://download.jitsi.org stable/" > /etc/apt/sources.list.d/jitsi-stable.list
echo "--------------------------------------------------"
sleep 2


# Installing Jitsi VideoBridge
printhead
echo "--------------------------------------------------"
echo "Installing Jitsi VideoBridge"
apt-get update && apt-get install -y jitsi-videobridge2
echo "--------------------------------------------------"
sleep 2


# Enabling and Stop Jitsi-VideoBridge Service
printhead
echo "--------------------------------------------------"
echo "Enabling and Stop Jitsi-VideoBridge Service"
systemctl enable jitsi-videobridge2
systemctl stop jitsi-videobridge2
echo "--------------------------------------------------"
sleep 2


# Cleaning-up
printhead
echo "--------------------------------------------------"
echo "Cleaning-up"
apt-get autoremove -y --purge
apt-get clean
echo "--------------------------------------------------"
sleep 2


# Completed
printhead
echo "--------------------------------------------------"
echo "Completed, please continue to configure Jitsi VideoBridge"
echo "--------------------------------------------------"
sleep 2


# Done
exit 0