#!/bin/bash -e

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

if [ -d /usr/local/ncpa ]; then
    echo "NCPA will not be installed: /usr/local/ncpa already present"
    exit
fi
echo "INSTALL: NCPA is being installed..."


# 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

assets="https://assets.nagios.com/downloads/ncpa3/"

if [ "$distro" == "Debian" ] || [ "$distro" == "Ubuntu" ]; then
    pkgname="$pkgname.$archtype.deb"
else
    pkgname="$pkgname.$archtype.rpm"
fi

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

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

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/*
# Run initial configuration
php configure_ncpa.php

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

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