#!/bin/sh
#
#
####################################################################
# InfluxDB NEB module install 
####################################################################
# Copyright (c) 2026 Nagios Enterprises, LLC. All rights reserved.
####################################################################
#
#


pkgname=`grep pkgname= ../nagioscore/install  | cut -f2 -d"="`  

# printf "\n pkgname == $pkgname \n" 

if [ ! -d "../nagioscore/$pkgname/include" ]; then
    echo "Error: ../nagioscore/$pkgname/include directory not found"
    exit 0
else 
	cp -R ../nagioscore/"$pkgname"/include .
fi

if [ ! -d "../nagioscore/$pkgname/lib" ]; then
    echo "Error: ../nagioscore/nagios/lib directory not found"
    exit 0 
else   
    cp -R ../nagioscore/"$pkgname"/lib .
fi





# Ensure libcurl development headers are installed
if [ -f /etc/redhat-release ] || [ -f /etc/centos-release ]; then
    if ! rpm -q libcurl-devel > /dev/null 2>&1; then
        echo "libcurl-devel not found, installing..."
        yum install -y libcurl-devel
        if [ $? -ne 0 ]; then
            echo "Error: Failed to install libcurl-devel"
            exit 0
        fi
    fi
elif [ -f /etc/debian_version ]; then
    if ! dpkg -l libcurl4-openssl-dev 2>/dev/null | grep -q '^ii'; then
        echo "libcurl4-openssl-dev not found, installing..."
        apt-get install -y libcurl4-openssl-dev
        if [ $? -ne 0 ]; then
            echo "Error: Failed to install libcurl4-openssl-dev"
            exit 0
        fi
    fi
else
    echo "Warning: Unable to detect OS type, skipping libcurl dependency check"
fi

cd module || { echo "Error: modules directory not found"; exit 0; }

make
if [ $? -ne 0 ]; then
    echo "Error: make command failed"
    exit 0
fi

make install
if [ $? -ne 0 ]; then
    echo "Error: make install command failed"
    exit 0
fi

make clean
if [ $? -ne 0 ]; then
    echo "Error: make clean command failed"
    exit 0
fi

cd ..

if [ -d "/usr/local/nagiosxi/scripts" ]; then
    cp setup_influx.sh /usr/local/nagiosxi/scripts/
    if [ $? -ne 0 ]; then
        echo "Error: Failed to copy setup_influx.sh to /usr/local/nagiosxi/scripts/"
    else
    	echo "Copied setup_influx.sh to /usr/local/nagiosxi/scripts/"
    fi
fi
