#!/bin/bash -e

pkgname="ncpa-2.4.1"
distro="$1"
dist="$2"
ver="$3"

echo "INSTALL: NCPA is being upgraded..."


# Check architecture and make a complete package name
arch=$(arch)

if [ "$arch" == "x86_64" ]; then
    if [ "$distro" == "Debian" ] || [ "$distro" == "Ubuntu" ]; then
        archtype="amd64"
    else
        archtype="$arch"
    fi
else
    archtype="i386"
fi

ncpa_version=${pkgname#*-}
assets="https://assets.nagios.com/downloads/ncpa/archived/${ncpa_version}/"

if [ "$distro" == "Debian" ] || [ "$distro" == "Ubuntu" ]; then
    if [ "$dist" == "ubuntu20" ]; then
        pkgname="$pkgname.d9.$archtype.deb"
    elif [ "$distro" == "Ubuntu" ] || [ "$ver" == "8" ]; then
        pkgname="$pkgname.$archtype.deb"
    else
        pkgname="$pkgname.d$ver.$archtype.deb"
    fi
else
    pkgname="$pkgname.$dist.$archtype.rpm"
fi

# Download a new package
wget "$assets$pkgname"

mv /usr/local/ncpa/etc/ncpa.cfg /usr/local/ncpa/etc/ncpa.cfg.nlssave

if [ "$distro" == "Debian" ] || [ "$distro" == "Ubuntu" ]; then
    dpkg --force-confnew -i "$pkgname"
else
    yum localinstall -y "$pkgname"
fi

mv /usr/local/ncpa/etc/ncpa.cfg.nlssave /usr/local/ncpa/etc/ncpa.cfg

cp plugins/* /usr/local/ncpa/plugins/
chmod 755 /usr/local/ncpa/plugins/*
# This will still use the hardcoded names from NCPA's original installation
chown nagios:nagios /usr/local/ncpa/plugins/*

if [ `command -v systemctl` ]; then
    systemctl enable ncpa_listener
    systemctl restart ncpa_listener
    systemctl enable ncpa_passive
    systemctl restart ncpa_passive
fi

# It is okay!
echo "INSTALL: NCPA installed OK."
