#!/bin/bash -e

# This script will be run on upgrade and install
if [ -f "/usr/local/nagiosxi/etc/xi-sys.cfg" ]; then
    # Upgrading
    . /usr/local/nagiosxi/etc/xi-sys.cfg
else # installing
    . ../../xi-sys.cfg
fi

if [ "$distro" == "Ubuntu" ]; then
    # Installing the apt package also adds the chromium-browser command, installs as snap
    if [ "$dist" == "ubuntu22" ]; then
        apt install -y xdg-utils libatk1.0-0 libatk-bridge2.0-0 libxcomposite1 libxdamage1 libxrandr2 libgbm1 libasound2
    else
        apt install -y xdg-utils libatk1.0-0t64 libatk-bridge2.0-0t64 libxcomposite1 libxdamage1 libxrandr2 libgbm1 libasound2t64
    fi
    wget https://storage.googleapis.com/chrome-for-testing-public/149.0.7827.53/linux64/chrome-headless-shell-linux64.zip 
    mkdir -p /opt/google/chrome-for-testing/
    unzip chrome-headless-shell-linux64.zip -d /opt/google/chrome-for-testing
    sudo ln -s /opt/google/chrome-for-testing/chrome-headless-shell-linux64/chrome-headless-shell /usr/local/bin/chrome-headless-shell
    source ~/.bashrc
    rm chrome-headless-shell-linux64.zip
    # Enabling linger allows the cron user to effectively run as nagios with snaps
    # https://forum.snapcraft.io/t/system-slice-cron-service-is-not-a-snap-cgroup/30196/5
    loginctl enable-linger $nagiosuser 
elif [ "$distro" == "Debian" ]; then
    apt install -y xdg-utils libatk1.0-0 libatk-bridge2.0-0 libxkbcommon0 libxcomposite1 libxdamage1 libxrandr2 libgbm1 libasound2
    wget https://storage.googleapis.com/chrome-for-testing-public/149.0.7827.53/linux64/chrome-headless-shell-linux64.zip 
    mkdir -p /opt/google/chrome-for-testing/
    unzip chrome-headless-shell-linux64.zip -d /opt/google/chrome-for-testing
    sudo ln -s /opt/google/chrome-for-testing/chrome-headless-shell-linux64/chrome-headless-shell /usr/local/bin/chrome-headless-shell
    source ~/.bashrc
    rm chrome-headless-shell-linux64.zip
else
    dnf install -y xdg-utils atk at-spi2-atk libXcomposite libXdamage libXrandr libgbm alsa-lib
    wget https://storage.googleapis.com/chrome-for-testing-public/149.0.7827.53/linux64/chrome-headless-shell-linux64.zip 
    mkdir -p /opt/google/chrome-for-testing/
    unzip chrome-headless-shell-linux64.zip -d /opt/google/chrome-for-testing
    sudo ln -s /opt/google/chrome-for-testing/chrome-headless-shell-linux64/chrome-headless-shell /usr/local/bin/chrome-headless-shell
    source ~/.bashrc
    rm chrome-headless-shell-linux64.zip
fi
echo "INSTALL: Chromium installed OK."
