#!/bin/bash

# This assumes a BLANK Raspberry Pi Zero W that we can install our AstropotaPOD stuff onto

do_toilet() {
  echo "$*" | toilet -f standard -F metal
}

# 1. Update
echo "Updating repositories and ensuring we have the software we need..."
sudo apt -y update && sudo apt -y dist-upgrade && sudo apt -y autoremove

# 2. Make sure we have the software we need
echo "Installing toilet...I know.  Bear with me."
sudo apt -y install toilet figlet
do_toilet "Pre-reqs"
sudo apt -y install git snmp jq bc mosquitto-clients
sudo sed -i 's/^AcceptEnv LANG LC_\*/#AcceptEnv LANG LC_\*/g' /etc/ssh/sshd_config
sudo systemctl restart ssh
do_toilet "Pips (via apt)"
sudo apt -y install python3-requests python3-paho-mqtt

# 3. Go get some stuff
do_toilet "Log dir"
cd
mkdir logs
#do_toilet "Getting NWC2026-AstropotaPOD"
#[ ! -d "NWC2026-AstropotaPOD" ] && git clone https://git.everwatch.global/eloyd/NWC2026-AstropotaPOD

# 4. Install Nagios Plugins
do_toilet "Nagios Plugins"
if [ ! -f "/usr/local/nagios/libexec/check_http" ]; then
  cd
  tar xfz NWC2026-AstropotaPOD/nagios-plugins-2.5.tar.gz
  cd nagios-plugins-2.5
  ./configure
  make && sudo make install
fi

# 5. Install NCPA
do_toilet "NCPA Client"
if [ ! -f "/usr/local/ncpa/etc/ncpa.cfg" ]; then
  cd; cd NWC2026-AstropotaPOD
  sudo apt -y install ./ncpa_3.3.1-1_armhf.deb
  sudo sed -i -e "s/^community_string.*/community_string=AstropotamusWasHere/" /usr/local/ncpa/etc/ncpa.cfg
  sudo systemctl restart ncpa
fi

# 6. Install Nagios Mod Gearman
do_toilet "NMG Worker"
if [ ! -f "/usr/local/bin/nagios-mod-gearman-worker" ]; then
  cd
  git clone https://github.com/NagiosEnterprises/nagios-mod-gearman
  cd nagios-mod-gearman
  sudo apt -y install automake libncurses-dev gearman libgearman-dev help2man dctrl-tools libperl-dev g++ libltdl-dev pkgconf make dpkg-dev debhelper libssl-dev
  sudo ./autogen.sh
  sudo ./configure
  sudo make install
fi

# 7. Install check_ncpa clients
do_toilet "NCPA Clients"
cd; cd NWC2026-AstropotaPOD
sudo cp check_ncpa.py /usr/local/nagios/libexec
arch=$(uname -m)
file="check_ncpa.${arch}"
if [ -r "$file" ]; then
  echo "Will install $file, since it's here..."
  echo "==> Installing ${file} to /usr/local/nagios/libexec..."
  sudo install -d /usr/local/nagios/libexec
  sudo install -m 0755 ${file} /usr/local/nagios/libexec/check_ncpa
  echo "==> Installation complete!"
  echo "Installed to: /usr/local/nagios/libexec/check_ncpa"
else
echo ""
echo "###"
echo "###"
echo "###"
echo "### IMPORTANT:"
echo "###"
echo "### You must extract, compile, and install the check_ncpa_c.2.Mar-05-26.tgz beta code to /usr/local/nagios/libexec"
echo "###"
echo "### Failure to do so will result in service check failures that may be hard to diagnose."
echo "###"
echo "###"
echo "###"
echo ""
fi

# Test
#/usr/local/bin/nagios-mod-gearman-worker --debug=2 --server=192.168.123.16 --key=AstropotamusWasHere --hosts --services --hostgroup=PODhosts --servicegroup=PODservices
