# SPDX-License-Identifier: GPL-3.0-or-later
%global contentdir %{_datadir}/netdata
%global version @PACKAGE_VERSION@

#TODO: Temporary fix for the build-id error during go.d plugin set up
%global _missing_build_ids_terminate_build 0

# XXX: We are using automatic `Requires:` generation for libraries
# whenever possible, DO NOT LIST LIBRARY DEPENDENCIES UNLESS THE RESULTANT
# PACKAGE IS BROKEN WITHOUT THEM.
AutoReqProv: yes

# This is temporary and should eventually be resolved. This bypasses
# the default rhel __os_install_post which throws a python compile
# error.
%global __os_install_post %{nil}

# We don’t want LTO as it has a minimal performance impact at runtime
# but a huge impact on build times (we want our CI to not take multiple
# hours to finish).
%global _lto_cflags %nil

# Disable eBPF for architectures other than x86
%ifarch x86_64 i386
%global _have_ebpf 1
%else
%global _have_ebpf 0
%endif

# Disable FreeIPMI on Amazon Linux
%if 0%{?amzn}
%global _have_freeipmi 0
%else
%global _have_freeipmi 1
%endif

# Disable the NFACCT plugin on Amazon Linux
%if 0%{?amzn}
%global _have_nfacct 0
%else
%global _have_nfacct 1
%endif

# Mitigate the cross-distro mayhem by strictly defining the libexec destination
%define _prefix /usr
%define _sysconfdir /etc
%define _localstatedir /var
%define _libexecdir /usr/libexec
%define _libdir /usr/lib

# Fedora doesn’t define this, but other distros do
%{!?_presetdir:%global _presetdir %{_libdir}/systemd/system-preset}

# Redefine centos_ver to standardize on a single macro
%{?rhel:%global centos_ver %rhel}

#
# Conditional build:
%bcond_without  netns    # build with netns support (cgroup-network)

%if 0%{?fedora} || 0%{?rhel} >= 7 || 0%{?suse_version} >= 1140
%else
%undefine	with_netns
%endif

Summary:	Real-time performance monitoring, done right!
Name:		netdata
Version:	%{version}
Release:	1%{?dist}
License:	GPLv3+
Group:		Applications/System
Source0:	https://github.com/netdata/%{name}/releases/download/%{version}/%{name}-%{version}.tar.gz
URL:		http://my-netdata.io

# Remove conflicting EPEL packages
Obsoletes:  %{name}-conf
Obsoletes:  %{name}-data

# #####################################################################
# Core build/install/runtime dependencies
# #####################################################################

# Build dependencies
#
BuildRequires: gcc
BuildRequires: gcc-c++
BuildRequires: make
BuildRequires: git-core
BuildRequires: autoconf
%if 0%{?fedora} || 0%{?rhel} >= 7 || 0%{?suse_version} >= 1140
BuildRequires: autoconf-archive
%if 0%{?rhel} <= 8 && 0%{?amzn} < 2023
BuildRequires: autogen
%endif
%endif
BuildRequires: automake
BuildRequires: cmake
BuildRequires: pkgconfig
BuildRequires: curl
BuildRequires: findutils
BuildRequires: zlib-devel
BuildRequires: libuuid-devel
BuildRequires: libuv-devel >= 1
BuildRequires: openssl-devel
%if 0%{?suse_version}
BuildRequires: protobuf-devel
BuildRequires: libprotobuf-c-devel
BuildRequires: liblz4-devel
BuildRequires: libjson-c-devel
BuildRequires: libyaml-devel
%else
%if 0%{?fedora}
BuildRequires: protobuf-devel
BuildRequires: protobuf-c-devel
BuildRequires: lz4-devel
BuildRequires: json-c-devel
BuildRequires: libyaml-devel
%else
%if 0%{?centos_ver} >= 8
BuildRequires: protobuf-devel
BuildRequires: protobuf-c-devel
%endif
BuildRequires: lz4-devel
BuildRequires: json-c-devel
BuildRequires: libyaml-devel
%endif
%endif

# Core build requirements for service install
%if 0%{?suse_version}
BuildRequires: systemd-rpm-macros
%else
BuildRequires: systemd
%endif

# Runtime dependencies
#
%if 0%{?centos_ver} == 7 || 0%{?centos_ver} == 6
Requires: python
%else
%if 0%{?centos_ver} == 8
Requires: python38
%else
Requires: python3
%endif
%endif

# Core requirements for the install to succeed
Requires(pre): /usr/sbin/groupadd
Requires(pre): /usr/sbin/useradd

# #####################################################################
# Functionality-dependent package dependencies
# #####################################################################
# Note: Some or all of the Packages may be found in the EPEL repo,
# rather than the standard ones

# epbf dependencies
%if 0%{?_have_ebpf}
%if 0%{?suse_version}
BuildRequires:	libelf-devel
%else
BuildRequires:	elfutils-libelf-devel
%endif
%endif
# end - ebpf dependencies

# nfacct plugin dependencies
%if %{_have_nfacct}
BuildRequires:  libmnl-devel
%if 0%{?fedora} || 0%{?suse_version} >= 1140
BuildRequires:  libnetfilter_acct-devel
%endif
%endif

# end nfacct plugin dependencies

# freeipmi plugin dependencies
%if %{_have_freeipmi}
BuildRequires:  freeipmi-devel
%endif
# end - freeipmi plugin dependencies

# CUPS plugin dependencies
%if 0%{?centos_ver} != 6 && 0%{?centos_ver} != 7
BuildRequires: cups-devel >= 1.7
%endif
# end - cups plugin dependencies

# Prometheus remote write dependencies
BuildRequires: snappy-devel
# end - prometheus remote write dependencies

# #####################################################################
# End of dependency management configuration
# #####################################################################

%description
  netdata is the fastest way to visualize metrics. It is a resource
efficient, highly optimized system for collecting and visualizing any
type of realtime timeseries data, from CPU usage, disk activity, SQL
queries, API calls, web site visitors, etc.
  netdata tries to visualize the truth of now, in its greatest detail,
so that you can get insights of what is happening now and what just
happened, on your systems and applications.

%prep
%setup -q -n %{name}-%{version}
# Only bundle protobuf on CentOS 7 or earlier
%if 0%{?centos_ver:1}
%if %{centos_ver} < 8
export CFLAGS="${CFLAGS} -fPIC" && ${RPM_BUILD_DIR}/%{name}-%{version}/packaging/bundle-protobuf.sh ${RPM_BUILD_DIR}/%{name}-%{version}
%endif
%endif
%if 0%{?_have_ebpf}
%if 0%{?centos_ver:1}
%if %{centos_ver} < 8
export CFLAGS="${CFLAGS} -fPIC" && ${RPM_BUILD_DIR}/%{name}-%{version}/packaging/bundle-libbpf.sh ${RPM_BUILD_DIR}/%{name}-%{version} centos7
export CFLAGS="${CFLAGS} -fPIC" && ${RPM_BUILD_DIR}/%{name}-%{version}/packaging/bundle-ebpf-co-re.sh ${RPM_BUILD_DIR}/%{name}-%{version}
%else
export CFLAGS="${CFLAGS} -fPIC" && ${RPM_BUILD_DIR}/%{name}-%{version}/packaging/bundle-libbpf.sh ${RPM_BUILD_DIR}/%{name}-%{version} centos8
export CFLAGS="${CFLAGS} -fPIC" && ${RPM_BUILD_DIR}/%{name}-%{version}/packaging/bundle-ebpf-co-re.sh ${RPM_BUILD_DIR}/%{name}-%{version}
%endif
%else
export CFLAGS="${CFLAGS} -fPIC" && ${RPM_BUILD_DIR}/%{name}-%{version}/packaging/bundle-libbpf.sh ${RPM_BUILD_DIR}/%{name}-%{version} other
export CFLAGS="${CFLAGS} -fPIC" && ${RPM_BUILD_DIR}/%{name}-%{version}/packaging/bundle-ebpf-co-re.sh ${RPM_BUILD_DIR}/%{name}-%{version}
%endif
%endif

%build
# Conf step
autoreconf -ivf
%configure \
	%if 0%{!?_have_ebpf}
	--disable-ebpf
	%endif
	%if 0%{?centos_ver:1}
	%if %{centos_ver} < 8
	--with-bundled-protobuf \
	%endif
	%endif
	--prefix="%{_prefix}" \
	--sysconfdir="%{_sysconfdir}" \
	--localstatedir="%{_localstatedir}" \
	--libexecdir="%{_libexecdir}" \
	--libdir="%{_libdir}" \
	--with-zlib \
	--with-math \
	--with-user=netdata \
	--disable-dependency-tracking

# Build step
%{__make} %{?_smp_mflags}

%install

# ###########################################################
# Clear the directory, if already exists and install
rm -rf "${RPM_BUILD_ROOT}"
%{__make} %{?_smp_mflags} DESTDIR="${RPM_BUILD_ROOT}" install

install -m 644 -p system/netdata.conf "${RPM_BUILD_ROOT}%{_sysconfdir}/%{name}"

# ###########################################################
# Install updater script
install -m 755 -p packaging/installer/netdata-updater.sh "${RPM_BUILD_ROOT}%{_libexecdir}/%{name}/netdata-updater.sh"

# ###########################################################
# logrotate settings
install -m 755 -d "${RPM_BUILD_ROOT}%{_sysconfdir}/logrotate.d"
install -m 644 -p system/logrotate/netdata "${RPM_BUILD_ROOT}%{_sysconfdir}/logrotate.d/%{name}"

# ###########################################################
# Install freeipmi
%if %{_have_freeipmi}
install -m 4750 -p freeipmi.plugin "${RPM_BUILD_ROOT}%{_libexecdir}/%{name}/plugins.d/freeipmi.plugin"
%endif

# ###########################################################
# Install apps.plugin
install -m 4750 -p apps.plugin "${RPM_BUILD_ROOT}%{_libexecdir}/%{name}/plugins.d/apps.plugin"

# ###########################################################
# Install perf.plugin
install -m 4750 -p perf.plugin "${RPM_BUILD_ROOT}%{_libexecdir}/%{name}/plugins.d/perf.plugin"

# ###########################################################
# Install ebpf.plugin
%if 0%{?_have_ebpf}
install -m 4750 -p ebpf.plugin "${RPM_BUILD_ROOT}%{_libexecdir}/%{name}/plugins.d/ebpf.plugin"
%endif

# ###########################################################
# Install cups.plugin
%if 0%{?centos_ver} != 6 && 0%{?centos_ver} != 7
install -m 0750 -p cups.plugin "${RPM_BUILD_ROOT}%{_libexecdir}/%{name}/plugins.d/cups.plugin"
%endif

# ###########################################################
# Install slabinfo.plugin
install -m 4750 -p slabinfo.plugin "${RPM_BUILD_ROOT}%{_libexecdir}/%{name}/plugins.d/slabinfo.plugin"

# ###########################################################
# Install cache and log directories
install -m 755 -d "${RPM_BUILD_ROOT}%{_localstatedir}/cache/%{name}"
install -m 755 -d "${RPM_BUILD_ROOT}%{_localstatedir}/log/%{name}"

# ###########################################################
# Install registry directory
install -m 755 -d "${RPM_BUILD_ROOT}%{_localstatedir}/lib/%{name}/registry"

# ###########################################################
# Install netdata service
install -m 755 -d "${RPM_BUILD_ROOT}%{_unitdir}"
install -m 644 -p system/systemd/netdata.service "${RPM_BUILD_ROOT}%{_unitdir}/netdata.service"
install -m 755 -d "${RPM_BUILD_ROOT}%{_presetdir}"
install -m 644 -p system/systemd/50-netdata.preset "${RPM_BUILD_ROOT}%{_presetdir}/50-netdata.preset"

# ############################################################
# Package Go within netdata (TBD: Package it separately)
safe_sha256sum() {
	# Within the context of the installer, we only use -c option that is common between the two commands
	# We will have to reconsider if we start non-common options
	if command -v sha256sum >/dev/null 2>&1; then
		sha256sum $@
	elif command -v shasum >/dev/null 2>&1; then
		shasum -a 256 $@
	else
		fatal "I could not find a suitable checksum binary to use"
	fi
}

download_go() {
	url="${1}"
	dest="${2}"

	if command -v curl >/dev/null 2>&1; then
		curl -sSL --connect-timeout 10 --retry 3 "${url}" > "${dest}"
	elif command -v wget >/dev/null 2>&1; then
		wget -T 15 -O - "${url}" > "${dest}"
	else
		echo >&2
		echo >&2 "Downloading go.d plugin from '${url}' failed because of missing mandatory packages."
		echo >&2 "Either add packages or disable it by issuing '--disable-go' in the installer"
		echo >&2
		exit 1
	fi
}

install_go() {
	# When updating this value, ensure correct checksums in packaging/go.d.checksums
	GO_PACKAGE_VERSION="$(cat packaging/go.d.version)"
	ARCH_MAP=(
		'i386::386'
		'i686::386'
		'x86_64::amd64'
		'aarch64::arm64'
		'armv64::arm64'
		'armv6l::arm'
		'armv7l::arm'
		'armv5tel::arm'
	)

	if [ -z "${NETDATA_DISABLE_GO+x}" ]; then
		echo >&2 "Install go.d.plugin"
		ARCH=$(uname -m)
		OS=$(uname -s | tr '[:upper:]' '[:lower:]')

		for index in "${ARCH_MAP[@]}" ; do
			KEY="${index%%::*}"
			VALUE="${index##*::}"
			if [ "$KEY" = "$ARCH" ]; then
				ARCH="${VALUE}"
				break
			fi
		done
		tmp=$(mktemp -d /tmp/netdata-go-XXXXXX)
		GO_PACKAGE_BASENAME="go.d.plugin-${GO_PACKAGE_VERSION}.${OS}-${ARCH}.tar.gz"
		download_go "https://github.com/netdata/go.d.plugin/releases/download/${GO_PACKAGE_VERSION}/${GO_PACKAGE_BASENAME}" "${tmp}/${GO_PACKAGE_BASENAME}"
		download_go "https://github.com/netdata/go.d.plugin/releases/download/${GO_PACKAGE_VERSION}/config.tar.gz" "${tmp}/config.tar.gz"

		if [ ! -f "${tmp}/${GO_PACKAGE_BASENAME}" ] || [ ! -f "${tmp}/config.tar.gz" ] || [ ! -s "${tmp}/config.tar.gz" ] || [ ! -s "${tmp}/${GO_PACKAGE_BASENAME}" ]; then
			echo >&2 "Either check the error or consider disabling it by issuing '--disable-go' in the installer"
			echo >&2
			return 1
		fi

		grep "${GO_PACKAGE_BASENAME}\$" "packaging/go.d.checksums" > "${tmp}/sha256sums.txt" 2>/dev/null
		grep "config.tar.gz" "packaging/go.d.checksums" >> "${tmp}/sha256sums.txt" 2>/dev/null

		# Checksum validation
		if ! (cd "${tmp}" && safe_sha256sum -c "sha256sums.txt"); then

			echo >&2 "go.d plugin checksum validation failure."
			echo >&2 "Either check the error or consider disabling it by issuing '--disable-go' in the installer"
			echo >&2

			echo "go.d.plugin package files checksum validation failed."
			exit 1
		fi

		# Install files
		tar -xf "${tmp}/config.tar.gz" -C "${RPM_BUILD_ROOT}%{_libdir}/%{name}/conf.d/"
		tar xf "${tmp}/${GO_PACKAGE_BASENAME}"
		mv "${GO_PACKAGE_BASENAME/\.tar\.gz/}" "go.d.plugin"
		rm -rf "${tmp}"
	fi
	return 0
}
install_go
install -m 0640 -p go.d.plugin "${RPM_BUILD_ROOT}%{_libexecdir}/%{name}/plugins.d/go.d.plugin"

%if 0%{?_have_ebpf}
${RPM_BUILD_DIR}/%{name}-%{version}/packaging/bundle-ebpf.sh ${RPM_BUILD_DIR}/%{name}-%{version} ${RPM_BUILD_ROOT}%{_libexecdir}/%{name}/plugins.d
%endif

%pre

if ! getent group netdata > /dev/null; then
  groupadd --system netdata
fi

if ! getent passwd netdata > /dev/null; then
  useradd --system -g netdata --home %{contentdir} --no-create-home -s /sbin/nologin -c "Netdata pseudo user" netdata
fi

# I am not sure that the corresponding group names are exactly the same as in Debian, but we should start somewhere, shouldn't we?
for item in docker nginx varnish haproxy adm nsd proxy squid ceph nobody I2C; do
  if getent group $item > /dev/null 2>&1; then
    usermod -a -G $item netdata
  fi
done

%post
%if 0%{?suse_version}
%service_add_post netdata.service
%else
%systemd_post netdata.service
%endif

%preun
%if 0%{?suse_version}
%service_del_preun netdata.service
%else
%systemd_preun netdata.service
%endif

%postun
%if 0%{?suse_version}
%service_del_postun netdata.service
%else
%systemd_postun_with_restart netdata.service
%endif

%clean
rm -rf "${RPM_BUILD_ROOT}"

%files
%doc README.md
%{_sysconfdir}/%{name}
%config(noreplace) %{_sysconfdir}/%{name}/netdata.conf
%config(noreplace) %{_sysconfdir}/logrotate.d/%{name}
%dir %{_libdir}/%{name}
%dir %{_datadir}/%{name}
%{_libdir}/%{name}
%{_libdir}/%{name}/conf.d/
%{_libexecdir}/%{name}
%{_sbindir}/%{name}
%{_sbindir}/netdatacli
%{_sbindir}/netdata-claim.sh

%{_unitdir}/netdata.service
%{_presetdir}/50-netdata.preset

%defattr(0750,root,netdata,0750)

%dir %{_libexecdir}/%{name}/python.d
%dir %{_libexecdir}/%{name}/charts.d
%dir %{_libexecdir}/%{name}/plugins.d

%{_libexecdir}/%{name}/python.d
%{_libexecdir}/%{name}/plugins.d

%caps(cap_dac_read_search,cap_sys_ptrace=ep) %attr(0750,root,netdata) %{_libexecdir}/%{name}/plugins.d/apps.plugin

%if %{with netns}
# cgroup-network detects the network interfaces of CGROUPs
# it must be able to use setns() and run cgroup-network-helper.sh as root
# the helper script reads /proc/PID/fdinfo/* files, runs virsh, etc.
%attr(4750,root,netdata) %{_libexecdir}/%{name}/plugins.d/cgroup-network
%attr(0750,root,netdata) %{_libexecdir}/%{name}/plugins.d/cgroup-network-helper.sh
%endif

# ebpf plugin
%if 0%{?_have_ebpf}
%attr(4750,root,netdata) %{_libexecdir}/%{name}/plugins.d/ebpf.plugin
%endif

# perf plugin
# This should be CAP_PERFMON once RPM finally learns about it, but needs to be CAP_SYS_ADMIN for now.
# %caps(cap_perfmon=ep) %attr(0750,root,netdata) %{_libexecdir}/%{name}/plugins.d/perf.plugin
%caps(cap_sys_admin=ep) %attr(0750,root,netdata) %{_libexecdir}/%{name}/plugins.d/perf.plugin

# perf plugin
%caps(cap_dac_read_search=ep) %attr(0750,root,netdata) %{_libexecdir}/%{name}/plugins.d/slabinfo.plugin

# go.d.plugin (the capability required for wireguard module)
%caps(cap_net_admin,cap_net_raw=eip) %{_libexecdir}/%{name}/plugins.d/go.d.plugin

# Enforce 0644 for files and 0755 for directories
# for the netdata web directory
%defattr(0644,root,root,0755)
%{_datadir}/%{name}/web

# Enforce 0660 for files and 0770 for directories
# for the netdata lib, cache and log dirs
%defattr(0660,root,netdata,0770)
%attr(0770,netdata,netdata) %dir %{_localstatedir}/cache/%{name}
%attr(0755,netdata,root) %dir %{_localstatedir}/log/%{name}
%attr(0770,netdata,netdata) %dir %{_localstatedir}/lib/%{name}
%attr(0770,netdata,netdata) %dir %{_localstatedir}/lib/%{name}/registry

# Free IPMI belongs to a different sub-package
%if %{_have_freeipmi}
%exclude %{_libexecdir}/%{name}/plugins.d/freeipmi.plugin
%endif

# CUPS belongs to a different sub package
%if 0%{?centos_ver} != 6 && 0%{?centos_ver} != 7
%exclude %{_libexecdir}/%{name}/plugins.d/cups.plugin

%package plugin-cups
Summary: The Common Unix Printing System plugin for netdata
Group: Applications/System
Requires: cups >= 1.7
Requires: netdata = %{version}

%description plugin-cups
 This is the Common Unix Printing System plugin for the netdata daemon.
Use this plugin to enable metrics collection from cupsd, the daemon running when CUPS is enabled on the system

%files plugin-cups
%attr(0750,root,netdata) %{_libexecdir}/%{name}/plugins.d/cups.plugin
%endif

%if %{_have_freeipmi}
%package plugin-freeipmi
Summary: FreeIPMI - The Intelligent Platform Management System
Group: Applications/System
Requires: freeipmi
Requires: netdata = %{version}

%description plugin-freeipmi
 The IPMI specification defines a set of interfaces for platform management.
It is implemented by a number vendors for system management. The features of IPMI that most users will be interested in
are sensor monitoring, system event monitoring, power control, and serial-over-LAN (SOL).

%files plugin-freeipmi
%attr(4750,root,netdata) %{_libexecdir}/%{name}/plugins.d/freeipmi.plugin
%endif

%changelog
* Tue Mar 21 2023 Austin Hemmelgarn <austin@netdata.cloud> 0.0.0-18
- Fix systemd handling to follow BCP.
- Drop pre-systemd init support.
* Thu Feb 16 2023 Konstantin Shalygin <k0ste@k0ste.ru> 0.0.0-17
- Added eBPF build dependency
* Fri Feb 03 2022 Austin Hemmelgarn <austin@netdata.cloud> 0.0.0-16
- Bundle updater script in native packages.
* Mon Oct 11 2021 Austin Hemmelgarn <austin@netdata.cloud> 0.0.0-15
- Remove support code for legacy ACLK implementation.
* Wed Sep 16 2020 Austin Hemmelgarn <austin@netdata.cloud> 0.0.0-14
- Convert to using 'AutoReq: yes' for library dependencies.
* Thu Feb 13 2020 Austin Hemmelgarn <austin@netdata.cloud> 0.0.0-13
- Add handling for custom libmosquitto fork
* Wed Jan 01 2020 Austin Hemmelgarn <austin@netdata.cloud> 0.0.0-12
- Add explicit installation of log and cache directories
- Clean up build dependencies.
* Thu Dec 19 2019 Austin Hemmelgarn <austin@netdata.cloud> 0.0.0-11
- Fix remaining ownership and permissions issues.
* Mon Nov 04 2019 Konstantinos Natsakis <konstantinos.natsakis@gmail.com> 0.0.0-10
- Fix /etc/netdata permissions
* Mon Sep 23 2019 Konstantinos Natsakis <konstantinos.natsakis@gmail.com> 0.0.0-9
- Do not build CUPS plugin subpackage on CentOS 6 and CentOS 7
* Tue Aug 20 2019 Pavlos Emm. Katsoulakis <paul@netdat.acloud> - 0.0.0-8
- Split CUPS functionality on separate package
* Fri Jun 28 2019 Pavlos Emm. Katsoulakis <paul@netdata.cloud> - 0.0.0-7
- Raise the path overrides to the spec file level, not just the configure.
- Adjust tighter permissions on some folders, based on what we did on our installer
- Introduce go.d plugin download and install, to include it on the package (Temporarily, to become separate package on next iteration)
* Tue Jun 25 2019 Pavlos Emm. Katsoulakis <paul@netdata.cloud> - 0.0.0-6
- Adjust dependency list: Some packages are missing on some distros, adopt to build successfully
* Mon Jun 24 2019 Pavlos Emm. Katsoulakis <paul@netdata.cloud> - 0.0.0-5
Another pass on cleaning up pre/post installation steps
- Sync permission and ownership on files and directories
* Sun Jun 16 2019 Pavlos Emm. Katsoulakis <paul@netdata.cloud> - 0.0.0-4
First draft refactor on package dependencies section
- Remove freeipmi/nfacct plugin flags. We auto-detect all plugins by decision
- Start refactor of package dependencies
- Add missing dependencies, with respect to distro peculiarities
- Adjust existing dependencies, so that distro-specific package names is applied
* Wed Jan 02 2019 Pawel Krupa <pkrupa@redhat.com> - 0.0.0-3
- Temporary set version statically
- Fix changelog ordering
- Comment-out node.d configuration directory
* Wed Jan 02 2019 Pawel Krupa <pkrupa@redhat.com> - 0.0.0-2
- Fix permissions for log files
* Sun Nov 15 2015 Alon Bar-Lev <alonbl@redhat.com> - 0.0.0-1
- Initial add.
