# COPR Ligenix's spec file for librenms
#
# This spec file is mostly the doc file
#
# Copyright (c) 2023-2024 Jean-Marc Liger
#
# License: CC-BY-SA
# http://creativecommons.org/licenses/by-sa/4.0/
#
# Please, preserve the changelog entries
#

%global with_selinux 1

%global with_monitor 1
%if 0%{?rhel} == 8
%if "%{_arch}" == "x86_64"
%global with_monitor 1
%else
%global with_monitor 0
%endif
%endif
%if 0%{?rhel} == 7
%global with_monitor 0
%endif

%if 0%{?fedora} || 0%{?rhel} >= 8
# httpd 2.4 with httpd-filesystem
%global with_httpd 1
# nginx 1.6 with nginx-filesystem
%global with_nginx 1
%else
%global with_httpd 0
%global with_nginx 0
%endif

%global version_release 24.11.0
%global vendor_install 20241121

%global version_string %{version_release}-%{vendor_install}
%global version_major %(ver=%{version_string}; echo ${ver%.*.*})


Name:           librenms
Version:        %{lua:ver = string.gsub(rpm.expand("%{version_string}"), "-", "~"); print(ver)}
Release:        1%{?dist}

Summary:        LibreNMS Autodiscovering PHP/MySQL/SNMP based network monitoring
Summary(fr):    LibreNMS Autodécouverte et surveillance réseau basée sur PHP/MySQL/SNMP

License:        GPLv3+
URL:            https://www.librenms.org/
#Source0:       https://github.com/librenms/librenms/archive/refs/tags/{version_release}.tar.gz
#Source1:       https://github.com/librenms/librenms-agent.git
#Source2:       https://github.com/librenms-plugins/Weathermap.git
Source:         %{name}-%{version_string}.tar.xz

BuildArch:      noarch
BuildRequires:  gettext
BuildRequires:  systemd

%if %{with_monitor}
%if %{with_httpd}
Requires:       httpd-filesystem
%endif
%if %{with_nginx}
Requires:       nginx-filesystem
%endif
%if %{with_httpd} || %{with_nginx}
Requires:       webserver
Requires:       php(httpd)
%else
Requires:       httpd
Requires:       mod_php
%endif

Requires:       php(language) >= 8.2.0
Requires:       php-fpm
Requires:       php-cli
Requires:       php-common
Requires:       php-curl
Requires:       php-gd
Requires:       php-gmp
Requires:       php-json
Requires:       php-mbstring
Requires:       php-pdo
Requires:       php-mysqlnd
Requires:       php-process
%if %{with_selinux}
Requires:       php-selinux
%endif
Requires:       php-snmp
Requires:       php-xml
Requires:       php-zip
Requires:       ImageMagick
%if 0%{?fedora} || 0%{?rhel} >= 8
# optional
Recommends:     php-ldap
Recommends:     php-opcache
%endif

Requires:       python3
Requires:       python3-async-timeout >= 4.0.2
Requires:	python3-command-runner >= 1.3.0
Requires:       python3-deprecated >= 1.2.3
Requires:       python3-dotenv
Requires:       python3-memcached
Requires:       python3-packaging >= 20.4
Requires:       python3-pip
Requires:       python3-psutil >= 5.6.0
Requires:       python3-PyMySQL
Requires:       python3-pyparsing >= 2.0.2
Requires:       python3-redis >= 4.0
Requires:       python3-setuptools
Requires:       python3-systemd
%if 0%{?fedora} || 0%{?rhel} >= 8
Requires:      (python3-wrapt >= 1.10 with python3-wrapt < 2) 
%else
Requires:       python3-wrapt >= 1.10
Requires:       python3-wrapt  < 2 
%endif

# MySQL or MariaDB server
Requires:       /usr/sbin/mysqld

Requires:       bash-completion
Requires:       fping
Requires:       mtr
Requires:       net-snmp
Requires:       net-snmp-utils
Requires:       nmap 
Requires:       rrdtool
Requires:       unzip

Requires:       cronie

%if 0%{?fedora} || 0%{?rhel} >= 8
%if 0%{?with_selinux}
# This ensures that the *-selinux package and all it’s dependencies are
# not pulled into containers and other systems that do not use SELinux
Requires:       (%{name}-selinux if selinux-policy-%{selinuxtype})
%endif
%endif

Requires:       %{name}-common = %{version}-%{release}
Requires:       %{name}-snmp-agent = %{version}-%{release}
Requires:       user(%{name})
Requires:       group(%{name})

Requires(pre):    group(%{name})
Requires(pre):    user(%{name})

Requires(pre):    systemd
Requires(post):   systemd
Requires(preun):  systemd
Requires(postun): systemd

Provides:       bundled(php-amqplib)
Provides:       bundled(php-assert)
Provides:       bundled(php-backtrace)
Provides:       bundled(php-base64url)
Provides:       bundled(php-bouncer)
Provides:       bundled(php-cache)
Provides:       bundled(php-carbon)
Provides:       bundled(php-collection)
Provides:       bundled(php-commonmark)
Provides:       bundled(php-config)
Provides:       bundled(php-console)
Provides:       bundled(php-console_color2)
Provides:       bundled(php-console_table)
Provides:       bundled(php-constant_time_encoding)
Provides:       bundled(php-container)
Provides:       bundled(php-cors)
Provides:       bundled(php-cron-expression)
Provides:       bundled(php-css-selector)
Provides:       bundled(php-css-to-inline-styles)
Provides:       bundled(php-dbal)
Provides:       bundled(php-deprecation-contracts)
Provides:       bundled(php-deprecations)
Provides:       bundled(php-doctrine-dbal)
Provides:       bundled(php-dot-access-data)
Provides:       bundled(php-email-validator)
Provides:       bundled(php-error-handler)
Provides:       bundled(php-event-dispatcher)
Provides:       bundled(php-event-dispatcher-contracts)
Provides:       bundled(php-event-manager)
Provides:       bundled(php-finder)
Provides:       bundled(php-flasher)
Provides:       bundled(php-flasher-laravel)
Provides:       bundled(php-flysystem)
Provides:       bundled(php-flysystem-local)
Provides:       bundled(php-framework)
Provides:       bundled(php-geshi)
Provides:       bundled(php-getallheaders)
Provides:       bundled(php-guzzle)
Provides:       bundled(php-htmlpurifier)
Provides:       bundled(php-http-client)
Provides:       bundled(php-http-factory)
Provides:       bundled(php-http-foundation)
Provides:       bundled(php-http-kernel)
Provides:       bundled(php-http-message)
Provides:       bundled(php-ignition)
Provides:       bundled(php-inflector)
Provides:       bundled(php-installed.json)
Provides:       bundled(php-jpgraph)
Provides:       bundled(php-json-schema)
Provides:       bundled(php-jwt-core)
Provides:       bundled(php-jwt-key-mgmt)
Provides:       bundled(php-jwt-signature)
Provides:       bundled(php-jwt-signature-algorithm-ecdsa)
Provides:       bundled(php-jwt-util-ecc)
Provides:       bundled(php-laravel-console-summary)
Provides:       bundled(php-laravel-ignition)
Provides:       bundled(php-laravel-pivot)
Provides:       bundled(php-laravel-vue-i18n-generator)
Provides:       bundled(php-lexer)
Provides:       bundled(php-log)
Provides:       bundled(php-mailer)
Provides:       bundled(php-manager)
Provides:       bundled(php-math)
Provides:       bundled(php-mime)
Provides:       bundled(php-mime-type-detection)
Provides:       bundled(php-monolog)
Provides:       bundled(php-net_dns2)
Provides:       bundled(php-oauth1-client)
Provides:       bundled(php-parse)
Provides:       bundled(php-parser)
Provides:       bundled(php-patch-type-declarations)
Provides:       bundled(php-phpdotenv)
Provides:       bundled(php-phpmailer)
Provides:       bundled(php-phpoption)
Provides:       bundled(php-phpseclib)
Provides:       bundled(php-pki-framework)
Provides:       bundled(php-polyfill-ctype)
Provides:       bundled(php-polyfill-intl-grapheme)
Provides:       bundled(php-polyfill-intl-idn)
Provides:       bundled(php-polyfill-intl-normalizer)
Provides:       bundled(php-polyfill-mbstring)
Provides:       bundled(php-polyfill-uuid)
Provides:       bundled(php-portable-ascii)
Provides:       bundled(php-predis)
Provides:       bundled(php-process)
Provides:       bundled(php-promises)
Provides:       bundled(php-psr7)
Provides:       bundled(php-psysh)
Provides:       bundled(php-purifier)
Provides:       bundled(php-radius)
Provides:       bundled(php-random_compat)
Provides:       bundled(php-result-type)
Provides:       bundled(php-routing)
Provides:       bundled(php-schema)
Provides:       bundled(php-serializable-closure)
Provides:       bundled(php-service-contracts)
Provides:       bundled(php-simple-cache)
Provides:       bundled(php-socialite)
Provides:       bundled(php-socket-raw)
Provides:       bundled(php-string)
Provides:       bundled(php-tcpdf)
Provides:       bundled(php-termwind)
Provides:       bundled(php-tinker)
Provides:       bundled(php-translation)
Provides:       bundled(php-translation-contracts)
Provides:       bundled(php-ui)
Provides:       bundled(php-uid)
Provides:       bundled(php-uri-template)
Provides:       bundled(php-utils)
Provides:       bundled(php-uuid)
Provides:       bundled(php-validate-json)
Provides:       bundled(php-var-dump-server)
Provides:       bundled(php-var-dumper)
Provides:       bundled(php-web-push)
Provides:       bundled(php-webpush)
Provides:       bundled(php-yaml)
Provides:       bundled(php-yaml-lint)
Provides:       bundled(php-ziggy)
%endif

%description
LibreNMS is an auto-discovering PHP/MySQL/SNMP based network monitoring tool
which includes support for a wide range of network hardware and operating systems
including Cisco, Linux, FreeBSD, Juniper, Brocade, Foundry, HP and many more.

We intend LibreNMS to be a viable project and community that:
- encourages contribution,
- focuses on the needs of its users, and
- offers a welcoming, friendly environment for everyone.

The Debian Social Contract will be the basis of our priority system,
and mutual respect is the basis of our behavior towards others.

%description -l fr
LibreNMS est un outil de surveillance de réseau à découverte automatique basé
sur PHP/MySQL/SNMP qui inclut la prise en charge d'une large gamme de matériel
réseau et de systèmes d'exploitation y compris Cisco, Linux, FreeBSD, Juniper,
Brocade, Foundry, HP et bien d'autres.

Nous souhaitons que LibreNMS soit un projet et une communauté viables qui :
- encourage la contribution,
- se concentre sur les besoins de ses utilisateurs, et
- offre un environnement accueillant et convivial pour tous.

Le contrat social Debian sera la base de notre système de priorités,
et le respect mutuel est la base de notre comportement envers les autres.


%package common
Summary:        Provides common directories, uid and gid among LibreNMS related packages
Requires(pre):  shadow-utils
Requires(post): shadow-utils
Provides:       user(%{name})
Provides:       group(%{name})

%description common
Provides common directories, uid and gid among LibreNMS related packages.

%description common -l fr


%if %{with_monitor}
%package rrdcached
Summary:        RRDCached support to create rrd files for LibreNMS
Summary(fr):    RRDCached support pour créer des fichiers rrd pour LibreNMS

Requires:       rrdtool
Requires:       %{name} = %{version}-%{release}
Requires:       user(%{name})
Requires:       group(%{name})

%description rrdcached
LibreNMS is an auto-discovering PHP/MySQL/SNMP based network monitoring tool
which includes support for a wide range of network hardware and operating systems
including Cisco, Linux, FreeBSD, Juniper, Brocade, Foundry, HP and many more.

This package provides support of RRDCached to create rrd files for LibreNMS.

%description rrdcached -l fr
LibreNMS est un outil de surveillance de réseau à découverte automatique basé
sur PHP/MySQL/SNMP qui inclut la prise en charge d'une large gamme de matériel
réseau et de systèmes d'exploitation y compris Cisco, Linux, FreeBSD, Juniper,
Brocade, Foundry, HP et bien d'autres.

Ce paquet fournit le support RRDCached pour créer des fichiers rrd pour LibreNMS.


%package snmptrap
Summary:        SNMP Traps reception for LibreNMS
Summary(fr):    SNMP Traps réception pour LibreNMS

Requires:       %{name} = %{version}-%{release}
Requires:       user(%{name})
Requires:       group(%{name})

%description snmptrap
LibreNMS is an auto-discovering PHP/MySQL/SNMP based network monitoring tool
which includes support for a wide range of network hardware and operating systems
including Cisco, Linux, FreeBSD, Juniper, Brocade, Foundry, HP and many more.

This package provides SNMP Traps reception for LibreNMS

%description snmptrap -l fr
LibreNMS est un outil de surveillance de réseau à découverte automatique basé
sur PHP/MySQL/SNMP qui inclut la prise en charge d'une large gamme de matériel
réseau et de systèmes d'exploitation y compris Cisco, Linux, FreeBSD, Juniper,
Brocade, Foundry, HP et bien d'autres.

Ce paquet fournit la réception des Traps SNMP pour LibreNMS


%package services
Summary:        Services to leverage the Nagios plugins for LibreNMS
Summary(fr):    Services d'exploitation des plugins Nagios pour LibreNMS

Requires:       %{name}-nagios-plugins
Requires:       %{name} = %{version}-%{release}
Requires:       user(%{name})
Requires:       group(%{name})

%description services
LibreNMS is an auto-discovering PHP/MySQL/SNMP based network monitoring tool
which includes support for a wide range of network hardware and operating systems
including Cisco, Linux, FreeBSD, Juniper, Brocade, Foundry, HP and many more.

This package provides the Services to leverage the Nagios plugins for LibreNMS.

%description services -l fr
LibreNMS est un outil de surveillance de réseau à découverte automatique basé
sur PHP/MySQL/SNMP qui inclut la prise en charge d'une large gamme de matériel
réseau et de systèmes d'exploitation y compris Cisco, Linux, FreeBSD, Juniper,
Brocade, Foundry, HP et bien d'autres.

Ce paquet fournit les Services d'exploitation des plugins Nagios pour LibreNMS.
%endif


%package check-mk-agent
Summary:        Check_MK agent for LibreNMS
Summary(fr):    Check_MK agent pour LibreNMS

Requires:       python3

Requires:       %{name}-common = %{version}-%{release}

%description check-mk-agent
LibreNMS is an auto-discovering PHP/MySQL/SNMP based network monitoring tool
which includes support for a wide range of network hardware and operating systems
including Cisco, Linux, FreeBSD, Juniper, Brocade, Foundry, HP and many more.

This package provides the Check_MK agent for LibreNMS.

%description check-mk-agent -l fr
LibreNMS est un outil de surveillance de réseau à découverte automatique basé
sur PHP/MySQL/SNMP qui inclut la prise en charge d'une large gamme de matériel
réseau et de systèmes d'exploitation y compris Cisco, Linux, FreeBSD, Juniper,
Brocade, Foundry, HP et bien d'autres.

Ce paquet fournit l'agent Check_MK pour LibreNMS.


%package snmp-agent
Summary:        SNMP agent for LibreNMS
Summary(fr):    SNMP agent pour LibreNMS

BuildRequires:  net-snmp
Requires:       net-snmp
Requires:       net-snmp-utils

Requires:       %{name}-common = %{version}-%{release}

%description snmp-agent
LibreNMS is an auto-discovering PHP/MySQL/SNMP based network monitoring tool
which includes support for a wide range of network hardware and operating systems
including Cisco, Linux, FreeBSD, Juniper, Brocade, Foundry, HP and many more.

This package provides the SNMP agent for LibreNMS.

%description snmp-agent -l fr
LibreNMS est un outil de surveillance de réseau à découverte automatique basé
sur PHP/MySQL/SNMP qui inclut la prise en charge d'une large gamme de matériel
réseau et de systèmes d'exploitation y compris Cisco, Linux, FreeBSD, Juniper,
Brocade, Foundry, HP et bien d'autres.

Ce paquet fournit l'agent SNMP pour LibreNMS.


%package snmp-extend
Summary:        SNMP extend for LibreNMS
Summary(fr):    SNMP extend pour LibreNMS

BuildRequires:  net-snmp
Requires:       net-snmp
Requires:       net-snmp-utils

Requires:       python2
Requires:       python3
Requires:       python3-pyOpenSSL
Requires:       python3-PyYAML
Requires:       python3-urllib3

Requires:       perl(MIME::Base64)
Requires:       perl(Gzip::Faster)

Requires:       %{name}-common = %{version}-%{release}
Requires:       %{name}-snmp-agent = %{version}-%{release}

%description snmp-extend
LibreNMS is an auto-discovering PHP/MySQL/SNMP based network monitoring tool
which includes support for a wide range of network hardware and operating systems
including Cisco, Linux, FreeBSD, Juniper, Brocade, Foundry, HP and many more.

This package provides the SNMP extend for LibreNMS.

%description snmp-extend -l fr
LibreNMS est un outil de surveillance de réseau à découverte automatique basé
sur PHP/MySQL/SNMP qui inclut la prise en charge d'une large gamme de matériel
réseau et de systèmes d'exploitation y compris Cisco, Linux, FreeBSD, Juniper,
Brocade, Foundry, HP et bien d'autres.

Ce paquet fournit des extensions SNMP pour LibreNMS.


%if %{with_monitor}
%package weathermap
Summary:        Network Weathermap for LibreNMS
Summary(fr):    Réseau Weathermap pour LibreNMS

Requires:       %{name}-common = %{version}-%{release}
Requires:       user(%{name})
Requires:       group(%{name})

%description weathermap
LibreNMS is an auto-discovering PHP/MySQL/SNMP based network monitoring tool
which includes support for a wide range of network hardware and operating systems
including Cisco, Linux, FreeBSD, Juniper, Brocade, Foundry, HP and many more.

This package provides the network Weathermap for LibreNMS.

%description weathermap -l fr
LibreNMS est un outil de surveillance de réseau à découverte automatique basé
sur PHP/MySQL/SNMP qui inclut la prise en charge d'une large gamme de matériel
réseau et de systèmes d'exploitation y compris Cisco, Linux, FreeBSD, Juniper,
Brocade, Foundry, HP et bien d'autres.

Ce paquet fournit le réseau Weathermap pour LibreNMS.
%endif


%prep
%setup -q -n %{name}-%{version_string}

# remove unused files
find . -name '.git*' -exec rm -r {} + -print
find . -name '*.xml*' -delete -print
find . -name '*.yml*' -delete -print
mv composer{.,_}json
find . -name 'composer.*' -delete -print
mv composer{_,.}json

# remove unnecessary files
rm misc/%{name}{-irc.init,.service.scl}
rm misc/smokeping-debian.example
rm -r scripts/agent-local

# remove cacti only files
rm html/plugins/Weathermap/lib/poller-common.php
rm -r html/plugins/Weathermap/random-bits

# remove already packaged files
rm LibreNMS/command_runner.py
sed -i -e "s/from [^ ]*\.command_runner/from command_runner/g" LibreNMS/*.py

# directories not in apache space
find html -name .htaccess -delete -print

# fix permission files
chmod -R g-w .
chmod -R o-rwx .
for d in bootstrap config LibreNMS dist includes mibs misc vendor
do find $d -type f -exec chmod 640 {} \;
done

# fix LSB directories
sed -i -e "s/cp \/opt/ls \/opt/g" LibreNMS/Validations/Scheduler.php
sed -i -e "s/\/opt\/librenms\/dist\/librenms/\%{_prefix}\/lib\/systemd\/system\/%{name}/g" LibreNMS/Validations/Scheduler.php
sed -i -e "s/ \/etc\/systemd\/system\///g" LibreNMS/Validations/Scheduler.php
sed -i -e "s/\/opt\/librenms\/logs/\%{_localstatedir}\/log\/%{name}/g" misc/%{name}.logrotate
sed -i -e '/}/s/^/    prerotate\n        bash -c "[[ ! $1 =~ *_*~*\.log ]]"\n    endscript\n/' misc/%{name}.logrotate

for f in $(grep -I -r "/opt/librenms/rrd" | cut -d":" -f1 | sort -u | grep -v "doc/"); do
        sed -i -e "s/\/opt\/librenms\/rrd/\%{_localstatedir}\/lib\/%{name}\/rrd/g" $f
done
for f in $(grep -I -r "/opt/librenms" | cut -d":" -f1 | sort -u | grep -v "doc/"); do
        sed -i -e "s/\/opt\/librenms/\%{_prefix}\/share\/%{name}/g" $f
done

# fix nagios-plugins directory
sed -i -e "s/\/nagios/\/librenms/g" tests/data/linux_sneck-v1.json
sed -i -e "s/\/plugins/\/nagios-plugins/g" tests/data/linux_sneck-v1.json

# fix python3-distro conflict
for f in $(grep -I -r "/usr/bin/distro" | cut -d":" -f1 | sort -u | grep -v "doc/"); do
        sed -i -e "s/\/usr\/bin\/\distro/\%{_prefix}\/bin\/%{name}_distro/g" $f
done

# fix snmp extend
for f in $(grep -I -r "/root/snmp-extends" agent/snmp | cut -d":" -f1 | sort -u | grep -v "doc/"); do
        sed -i -e "s/\/root\/snmp-extends/\%{_prefix}\/%{_lib}\/%{name}\/snmp/g" $f
done
for f in $(grep -I -r "/usr/local/etc/snmp/extends" agent/snmp | cut -d":" -f1 | sort -u | grep -v "doc/"); do
        sed -i -e "s/\/usr\/local\/etc\/snmp\/\extends/\%{_prefix}\/%{_lib}\/%{name}\/snmp/g" $f
done
for f in $(grep -I -r "/etc/snmp/extends" agent/snmp | cut -d":" -f1 | sort -u | grep -v "doc/"); do
        sed -i -e "s/\/etc\/snmp\/\extends/\%{_prefix}\/%{_lib}\/%{name}\/snmp/g" $f
done
for f in $(grep -I -r "/etc/snmp" agent/snmp | cut -d":" -f1 | sort -u | grep -v "doc/"); do
        sed -i -e "s/\/etc\/snmp/\%{_prefix}\/%{_lib}\/%{name}\/snmp/g" $f
done

%if 0%{?rhel} == 7
sed -i -e 's/f"{error_name}: '\''{err}'\''"/"%s: '\''%s'\''" % (error_name, err)/g' agent/snmp/{linux_iw,ss}.py
%endif

# add snmp subagent
echo -e $"\n#AgentX subagent\nmaster agentx\nagentXSocket   tcp:localhost:705" >> snmpd.conf.example

# change Check_Mk directories
for f in $(grep -I -r "/lib/check_mk" agent | cut -d":" -f1 | sort -u); do
        sed -i -e "s/\/lib\/check_mk/\/lib\/%{name}\/check_mk/g" $f
done
for f in $(grep -I -r "/etc/check_mk" agent | cut -d":" -f1 | sort -u); do
        sed -i -e "s/\/etc\/check_mk/\/etc\/%{name}\/check_mk/g" $f
done

# fix some mangling shebang
for f in $(grep -I -r "/usr/local/bin" | cut -d":" -f1 | sort -u | grep -v "doc/"); do
        sed -i -e "s/usr\/local\/bin/usr\/bin\//g" $f
done
for f in $(grep -I -r "/usr/bin/env " | cut -d":" -f1 | sort -u | grep -v "doc/"); do
        sed -i -e "s/usr\/bin\/env /usr\/bin\//g" $f
done
for f in $(grep -I -r "!/usr/bin/python" agent | grep -v python2 | grep -v python3 | cut -d":" -f1); do
        sed -i -e "s/!\/usr\/bin\/python/!\/usr\/bin\/python3/g" $f
done
for f in $(grep -I -r "!/bin/" | cut -d":" -f1); do
        sed -i -e "s/!\/bin\//!\/usr\/bin\//g" $f
done

%if %{with_monitor}
# fix config
mv config.php{.default,}
sed -i -e "/config_definitions.json!/s/^/## LSB directories\n\$config['install_dir'] = '\%{_prefix}\/share\/%{name}';\n\$config['log_dir']     = '\%{_localstatedir}\/log\/%{name}';\n\$config['rrd_dir']     = '\%{_localstatedir}\/lib\/%{name}\/rrd';\n\n/" config.php
sed -i -e "s/#\$config\['user/\$config\['user/g" config.php
sed -i -e "s/#\$config\['update/\$config\['update/g" config.php
sed -i '$d' config.php
echo $"if (file_exists('%{_sysconfdir}/%{name}/config-services.php'))" >> config.php
echo $"   include_once('%{_sysconfdir}/%{name}/config-services.php');" >> config.php

# fix weathermap config
for f in html/plugins/Weathermap/*.php; do
        sed -i -e "s/'config.inc.php'/'\%{_sysconfdir}\/%{name}\/config-weathermap.php'/g" $f
done
sed -i -e "s/'configs\/'/'config-weathermap\/'/g" html/plugins/Weathermap/config.inc.php
sed -i -e "s/realpath(dirname(__FILE__) . '\/..\/..\/..\/')/'\%{_prefix}\/share\/%{name}'/g" html/plugins/Weathermap/config.inc.php
sed -i -e "s/\$librenms_base . '\/'.'/'\%{_localstatedir}\/lib\/%{name}\//g" html/plugins/Weathermap/config.inc.php
sed -i -e "s/'plugins\/Weathermap\/configs'/'\%{_sysconfdir}\/%{name}\/config-ueathermap'/g" html/plugins/Weathermap/Weathermap.inc.php
sed -i -e "s/\$conf_dir/\$mapdir/g" html/plugins/Weathermap/map-poller.php

# rename bash completion
sed -i -e "s/'lnms-completion.bash'/'lnms'/g" LibreNMS/Validations/System.php

# list composer dependencies
ls vendor/*/ | grep -v / | grep -v \.php | grep -v LICENSE | sed 's/php-//g' | sort -u | sed -e 's/.*/Provides:       bundled(php-&)/' | grep -v php-\)

cat >httpd <<EOF
#Alias /%{name} %{_datadir}/%{name}/html

# some people prefer a simple URL like http://%{name}.example.com
<VirtualHost *:80>
    ServerName %{name}.example.com
    DocumentRoot %{_datadir}/%{name}/html

AllowEncodedSlashes NoDecode
<Directory %{_datadir}/%{name}/html>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All

    AddType image/svg+xml .svg
    <IfModule mod_filter.c>
        <IfModule mod_deflate.c>
             AddOutputFilterByType DEFLATE text/css
             AddOutputFilterByType DEFLATE application/javascript
             AddOutputFilterByType DEFLATE text/javascript
             AddOutputFilterByType DEFLATE application/x-javascript
             AddOutputFilterByType DEFLATE image/svg+xml
             AddOutputFilterByType DEFLATE text/plain
             AddOutputFilterByType DEFLATE text/xsd
             AddOutputFilterByType DEFLATE text/xsl
             AddOutputFilterByType DEFLATE text/xml
             AddOutputFilterByType DEFLATE image/x-icon
        </IfModule>
    </IfModule>

    RewriteEngine on
    #RewriteBase /librenms/
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !\.(js|ico|txt|gif|jpg|png|css|php)
    RewriteRule ^api/v0(.*)$ api_v0.php/$1 [L]
    RewriteCond %{REQUEST_URI} !=/server-status
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !\.(js|ico|txt|gif|jpg|png|css|php)
    RewriteRule ^(.*)$ index.php

    AcceptPathInfo On

    <IfModule mod_authz_core.c>
        Require all granted
    </IfModule>
    <IfModule !mod_authz_core.c>
        Order deny,allow
        Allow from all
    </IfModule>
</Directory>

# Enable http authorization headers
<IfModule setenvif_module>
    SetEnvIfNoCase ^Authorization$ "(.+)" HTTP_AUTHORIZATION=$1
</IfModule>

<FilesMatch ".+\.php$">
    SetHandler "proxy:unix:/run/php-fpm/librenms.sock|fcgi://localhost"
</FilesMatch>

</VirtualHost>
EOF

cat >nginx <<EOF
charset utf-8;

gzip on;
gzip_types text/css application/javascript text/javascript application/x-javascript image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;

location / {
    try_files $uri $uri/ /index.php?$query_string;
 }

location ~ [^/]\.php(/|$) {
    fastcgi_pass unix:/run/php-fpm-librenms.sock;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    include fastcgi.conf;
}

location ~ /\.(?!well-known).* {
    deny all;
}
:
# some people prefer a simple URL like http://%{name}.example.com
#server {
#    listen      80;
#    server_name %{name}.example.com;
#    root        %{_datadir}/%{name}/html;
#    index       index.php;
#}
EOF

cat >rrdcached-systemd <<EOF
[Unit]
Description=Data caching daemon for rrdtool
After=network.service

[Service]
Type=forking
PIDFile=/run/rrdcached.pid
ExecStart=%{_bindir}/rrdcached -w 1800 -z 1800 -f 3600 -s %{name} -U %{name} -G %{name} -B -R -j /%{_localstatedir}/tmp -l unix:/run/rrdcached.sock -t 4 -F -b %{_localstatedir}/lib/%{name}/rrd/

[Install]
WantedBy=default.target
EOF

cat >snmptrap-systemd <<EOF
[Unit]
Description=Simple Network Management Protocol (SNMP) Trap Daemon.
After=syslog.target network-online.target
ConditionPathExists=%{_sysconfdir}/snmp/conf.d/%{name}-trapd.conf

[Service]
Type=notify
Environment="MIBSDIR=%{_datadir}/%{name}/mibs"
ExecStart=%{_sbindir}/snmptrapd -f -m IF-MIB -M %{_datadir}/%{name}/mibs -tLf %{_localstatedir}/log/%{name}/snmptrap.log
ExecReload=/bin/kill -HUP $MAINPID

[Install]
WantedBy=multi-user.target
EOF

cat >snmptrap-config <<EOF
disableAuthorization yes
authCommunity log,execute,net COMMUNITYSTRING
traphandle default %{_datadir}/%{name}/snmptrap.php
EOF

cat >services-config <<EOF
<?php

\$config['show_services']               = 1;

\$config['discover_services']           = true;
\$config['discover_services_templates'] = true;

\$config['nagios_plugins'] = "%{_libdir}/%{name}/nagios-plugins";

\$config['service_poller_enabled']      = true;
\$config['service_poller_workers']      = 16;
\$config['service_poller_frequency']    = 300;
\$config['service_poller_down_retry']   = 5;

\$config['service_discovery_enabled']   = true;
\$config['service_discovery_workers']   = 16;
\$config['service_discovery_frequency'] = 3600;

\$config['service_services_enabled']    = true;
\$config['service_services_workers']    = 16;
\$config['service_services_frequency']  = 60;
EOF

cat >services-cron <<EOF
*/5  *    * * *   %{name}    %{_datadir}/%{name}/services-wrapper.py 1
EOF
%endif

cat >check_mrpe <<EOF
#cpu_check %{_datadir}/%{name}/nagios-plugins/check_cpu.sh -c 95 -w 75
EOF

cat >snmp-extend <<EOF

# Applications support
# (uncomment to graph performance statistics)
# extend bind %{_libdir}/%{name}/snmp/bind
# extend cape %{_libdir}/%{name}/snmp/cape
# extend exim-stats %{_libdir}/%{name}/snmp/exim-stats.sh
# extend fail2ban %{_libdir}/%{name}/snmp/fail2ban -c -U -f /usr/bin/fail2ban-client
# extend fbsdnfsclient %{_libdir}/%{name}/snmp/fbsdnfsclient
# extend fbsdnfsserver %{_libdir}/%{name}/snmp/fbsdnfsserver
# extend linux_config_files %{_libdir}/%{name}/snmp/linux_config_files.py
# extend linux_iw %{_libdir}/%{name}/snmp/linux_iw.py
# extend logsize %{_libdir}/%{name}/snmp/logsize -b
# extend nvidia %{_libdir}/%{name}/snmps/nvidia
# extend opensearch %{_libdir}/%{name}/snmp/opensearch
# extend osupdate %{_libdir}/%{name}/snmp/osupdate
# extend phpfpmsp %{_libdir}/%{name}/snmp/phpfpm-sp
# extend portactivity %{_libdir}/%{name}/snmp/portactivity -p http,ssh
# extend postfixdetailed %{_libdir}/%{name}/snmp/postfixdetailed
# extend privoxy %{_libdir}/%{name}/snmp/privoxy
# extend pwrstatd %{_libdir}/%{name}/snmp/pwrstatd.py
# extend smart %{_libdir}/%{name}/snmp/smart
# extend ss %{_libdir}/%{name}/snmp/ss.py
# extend systemd %{_libdir}/%{name}/snmp/systemd.py
# extend unbound %{_libdir}/%{name}/snmp/unbound
# extend ups-apcups %{_libdir}/%{name}/snmp/ups-apcups
# extend ups-apcups %{_libdir}/%{name}/snmp/ups-apcups.sh
# extend ups-nut %{_libdir}/%{name}/snmp/ups-nut.sh
# extend wireguard %{_libdir}/%{name}/snmp/wireguard.py
# extend zfs %{_libdir}/%{name}/snmp/zfs-linux
EOF

%if %{with_monitor}
cat >weathermap-cron <<EOF
*/5  *    * * *   %{name}    %{_datadir}/%{name}/htm/plugins/Weathermap/map-poller.php >> /dev/null 2>&1
EOF

cat >readme <<EOF
This package has been build with security enhanced by design:

The LibreNMS %{version} source code has been patch to be LSB compliant, easy to install with full SELinux support.

The settings were moved outside of the DocumentRoot in %{_sysconfdir}/%{name} repository.

The private data store was automatically predefined as The %{_localstatedir}/lib/%{name}/library repository.

Installation with apache is now configured to be done under localhost/librenms.

Required CLI configuration for LibreNMS:

timedatectl set-timezone Europe/Paris

edit file %{_syconfdir}/php.ini:
date.timezone = Europe/Paris

edit file %{_syconfdir}/my.cnf.d/mariadb-server.cnf in the [Mysqld] section :
innodb_file_per_table=1
lower_case_table_names=0

systemctl enable [mariadb|mysqld] [httpd|nginx] php-fpm %{name}-scheduler.timer
systemctl start [mariadb|mysqld] [httpd|nginx] php-fpm %{name}-scheduler.timer

mysql_secure_installation

mysql -u root -p
CREATE DATABASE %{name} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER '%{name}'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON %{name}.* TO '%{name}'@'localhost';
FLUSH PRIVILEGES;

Addtional CLI configuration fot LibreNMS with SELinux in enforcing mode and remote MariaDB/MySQL: 

setsebool -P httpd_can_network_connect_db on && getsebool -a | grep httpd | grep "> on"
EOF

%if %{with_selinux}
cat >http_fping.te <<EOF
module http_fping 1.0;

require {
type httpd_t;
type node_t;
class capability net_raw;
class rawip_socket { create read bind write setopt getopt node_bind };
}

#============= httpd_t ==============
allow httpd_t self:capability net_raw;
allow httpd_t self:rawip_socket { create read bind write setopt getopt };
allow httpd_t node_t:rawip_socket node_bind;
EOF

cat > rrdcached_librenms.te << EOF
module rrdcached_librenms 1.0;

require {
        type httpd_t;
        type httpd_var_lib_t;
        type rrdcached_t;
        type var_run_t;
        class capability { dac_read_search fsetid };
        class dir { add_name getattr remove_name search write };
        class file { create getattr lock map open read rename setattr write };
        class sock_file { create setattr unlink write };
        class unix_stream_socket connectto;
        class tcp_socket { accept listen };
        class tcp_socket name_connect;
        type ephemeral_port_t;
}

#============= httpd_t ==============
allow httpd_t rrdcached_t:unix_stream_socket connectto;
allow httpd_t var_run_t:sock_file write;
allow httpd_t ephemeral_port_t:tcp_socket name_connect;

#============= rrdcached_t ==============
allow rrdcached_t httpd_var_lib_t:dir { add_name getattr remove_name search write };
allow rrdcached_t httpd_var_lib_t:file map;
allow rrdcached_t httpd_var_lib_t:file { create getattr lock open read rename setattr write };
allow rrdcached_t self:capability { dac_read_search fsetid };
allow rrdcached_t var_run_t:sock_file { create setattr unlink };
allow rrdcached_t self:tcp_socket { accept listen };
EOF

cat > snmptrap_librenms.te << EOF
module snmptrap_librenms 1.0;

require {
        type httpd_sys_rw_content_t;
        type snmpd_t;
        class file { append getattr open read };
        class capability dac_override;
}

#============= snmpd_t ==============
allow snmpd_t httpd_sys_rw_content_t:file { append getattr open read };
allow snmpd_t self:capability dac_override;
EOF
%endif
%endif


%build


%install
# config
mkdir -p %{buildroot}%{_sysconfdir}/%{name}
mkdir -p %{buildroot}%{_datadir}/%{name}

%if %{with_monitor}
for df in config config.php .env
do cp -ar $df %{buildroot}%{_sysconfdir}/%{name}/$df
ln -sr %{_sysconfdir}/%{name}/$df %{buildroot}%{_datadir}/%{name}/$df
done

# application
for d in app database html includes lang LibreNMS mibs resources routes scripts tests vendor
do cp -ar $d %{buildroot}%{_datadir}/%{name}/$d
done
rm config.php
cp -a *.{js,php,py,sh} artisan composer.json cronic lnms requirements.txt %{buildroot}%{_datadir}/%{name}/
mkdir -p %{buildroot}%{_datadir}/%{name}/bootstrap
cp -a bootstrap/*.php %{buildroot}%{_datadir}/%{name}/bootstrap
mkdir -p %{buildroot}%{_datadir}/%{name}/misc
cp -a misc/*.{conf,json,rss,yaml} %{buildroot}%{_datadir}/%{name}/misc

# .cache, .config, .local, rrd
mkdir -p %{buildroot}%{_localstatedir}/lib/%{name}/{.cache,.config,.local,rrd}
for d in .cache .config .local rrd
do ln -sr %{_localstatedir}/lib/%{name}/$d %{buildroot}%{_datadir}/%{name}/$d
done
# cache, storage
cp -ar bootstrap/cache %{buildroot}%{_localstatedir}/lib/%{name}/cache
ln -sr %{_localstatedir}/lib/%{name}/cache %{buildroot}%{_datadir}/%{name}/bootstrap/cache
cp -ar storage %{buildroot}%{_localstatedir}/lib/%{name}/storage
ln -sr %{_localstatedir}/lib/%{name}/storage %{buildroot}%{_datadir}/%{name}/storage
%endif

# log
mkdir -p %{buildroot}%{_localstatedir}/log/%{name}

%if %{with_monitor}
ln -sr %{_localstatedir}/log/%{name} %{buildroot}%{_datadir}/%{name}/logs
touch %{buildroot}%{_localstatedir}/log/%{name}/{install,upgrade,services}_%{version}.log

# command
mkdir -p %{buildroot}%{_bindir}
ln -sr %{_datadir}/%{name}/lnms %{buildroot}%{_bindir}/lnms

# apache
install -Dpm 0644 httpd %{buildroot}%{_sysconfdir}/httpd/conf.d/%{name}.conf

# nginx
%if %{with_nginx}
install -Dpm 0644 nginx %{buildroot}%{_sysconfdir}/nginx/default.d/%{name}.conf
%endif

# php-fpm
mkdir -p %{buildroot}%{_sysconfdir}/php-fpm.d
touch %{buildroot}%{_sysconfdir}/php-fpm.d/%{name}.conf

# logrotate
install -Dpm 0644 misc/%{name}.logrotate %{buildroot}%{_sysconfdir}/logrotate.d/%{name}

# bash completion
install -Dpm 0644 misc/lnms-completion.bash %{buildroot}%{_sysconfdir}/bash_completion.d/lnms

# cron
install -Dpm 0644 dist/%{name}.cron %{buildroot}%{_sysconfdir}/cron.d/%{name}

# systemd
install -Dpm 0644 dist/%{name}-scheduler.service %{buildroot}%{_unitdir}/%{name}-scheduler.service
install -Dpm 0644 dist/%{name}-scheduler.timer %{buildroot}%{_unitdir}/%{name}-scheduler.timer

# rrdcached systemd
install -Dpm 0644 rrdcached-systemd %{buildroot}%{_unitdir}/%{name}-rrdcached.service

# snmptrap systemd
install -Dpm 0644 snmptrap-systemd %{buildroot}%{_unitdir}/%{name}-snmptrapd.service
%endif

mkdir -p %{buildroot}%{_sysconfdir}/snmp/conf.d

# snmptrap config
%if %{with_monitor}
install -Dpm 0644 snmptrap-config %{buildroot}%{_sysconfdir}/snmp/conf.d/%{name}-trapd.conf
%endif

# services plugins
mkdir -p %{buildroot}%{_libdir}/%{name}/nagios-plugins

%if %{with_monitor}
# services config
install -Dpm 0640 services-config %{buildroot}%{_sysconfdir}/%{name}/config-services.php

# services cron
install -Dpm 0644 services-cron %{buildroot}%{_sysconfdir}/cron.d/%{name}-services
%endif

# check_mk agent
mkdir -p %{buildroot}%{_sysconfdir}/%{name}/check_mk
install -Dpm 0644 check_mrpe %{buildroot}%{_sysconfdir}/%{name}/check_mk/mrpe.cfg

mkdir -p %{buildroot}%{_libdir}/%{name}/check_mk_agent/{local,plugins,repo}
cp -ar agent/agent-local/* %{buildroot}%{_libdir}/%{name}/check_mk_agent/repo/
rm %{buildroot}%{_libdir}/%{name}/check_mk_agent/repo/README

mkdir -p %{buildroot}%{_localstatedir}/lib/%{name}/check_mk_agent

install -Dpm 0750 agent/check_mk_agent %{buildroot}%{_bindir}/check_mk_agent
install -Dpm 0750 agent/mk_enplug %{buildroot}%{_bindir}/mk_enplug

install -Dpm 0644 agent/check_mk@.service %{buildroot}%{_unitdir}/check_mk@.service
install -Dpm 0644 agent/check_mk.socket %{buildroot}%{_unitdir}/check_mk.socket

# snmp agent
install -Dpm 0644 snmpd.conf.example %{buildroot}%{_sysconfdir}/snmp/conf.d/%{name}-agent.conf

install -Dpm 0750 agent/snmp/distro %{buildroot}%{_bindir}/%{name}_distro

# snmp extend
install -Dpm 0644 snmp-extend %{buildroot}%{_sysconfdir}/snmp/conf.d/%{name}-extend.conf

cp -ar agent/snmp %{buildroot}%{_libdir}/%{name}/snmp
rm %{buildroot}%{_libdir}/%{name}/snmp/distro

install -Dpm 0750 agent/utils/librenms_return_optimizer %{buildroot}%{_bindir}/librenms_return_optimizer

# check_mk, snmp extend cache
mkdir -p %{buildroot}%{_localstatedir}/cache/%{name}

%if %{with_monitor}
# weathermap config
cp -ar html/plugins/Weathermap/configs %{buildroot}%{_sysconfdir}/%{name}/config-weathermap
cp -a  html/plugins/Weathermap/config.inc.php %{buildroot}%{_sysconfdir}/%{name}/config-weathermap.php
rm -r  %{buildroot}%{_datadir}/%{name}/html/plugins/Weathermap/configs
rm     %{buildroot}%{_datadir}/%{name}/html/plugins/Weathermap/config.inc.php

# weathermap application
mv  %{buildroot}%{_datadir}/%{name}/html/plugins/Weathermap/output %{buildroot}%{_localstatedir}/lib/%{name}/
ln -sr %{_localstatedir}/lib/%{name}/output %{buildroot}%{_datadir}/%{name}/html/plugins/Weathermap/output

# weathermap cron
install -Dpm 0644 weathermap-cron %{buildroot}%{_sysconfdir}/cron.d/%{name}-weathermap

# doc
install -Dpm 0644 readme README.Fedora

# lang
for i in %{buildroot}%{_datadir}/%{name}/lang/*
do
  lang=$(basename $i)
  echo "%lang(${lang:0:2}) %attr(750,%{name},%{name}) %{_datadir}/%{name}/lang/${lang}"
done > %{name}.lang
%endif

%if %{with_selinux}
mkdir -p %{buildroot}%{_datadir}/%{name}/selinux
%if %{with_monitor}
for f in *.te
do install -Dpm 0644 $f %{buildroot}%{_datadir}/%{name}/selinux/$f
done
%endif
%endif


%pre common
getent group %{name} >/dev/null || groupadd -r %{name}
getent passwd %{name} >/dev/null || \
    useradd -M -r -g %{name} -d %{_datadir}/%{name} -s /bin/bash -c "User for LibreNMS monitoring tool" %{name}


%if %{with_monitor}
%post
%{_sbindir}/usermod -a -G %{name} apache || :
%{_sbindir}/usermod -a -G %{name} nginx || :

%if %{with_selinux}
(
# create librenms file context
semanage fcontext -a -s system_u -t httpd_sys_content_t    -r s0 "%{_datadir}/%{name}(/.*)?"
semanage fcontext -a -s system_u -t usr_t                  -r s0 "%{_datadir}/%{name}(/.*)?\.(pl|py|sh)$"
semanage fcontext -a -s system_u -t bin_t                  -r s0 "%{_datadir}/%{name}/librenms-service.py"
semanage fcontext -a -s system_u -t httpd_var_lib_t        -r s0 "%{_datadir}/%{name}/(.cache|.config|.local|rrd|storage)"
semanage fcontext -a -s system_u -t httpd_log_t            -r s0 "%{_datadir}/%{name}/logs"
semanage fcontext -a -s system_u -t httpd_var_lib_t        -r s0 "%{_localstatedir}/lib/%{name}/(.cache|.config|.local|rrd|storage)(/.*)?"
semanage fcontext -a -s system_u -t httpd_log_t            -r s0 "%{_localstatedir}/log/%{name}(/.*)?"
semanage fcontext -a -s system_u -t httpd_sys_rw_content_t -r s0 "%{_sysconfdir}/%{name}(/.*)?"
semanage fcontext -a -s system_u -t etc_t                  -r s0 "%{_sysconfdir}/%{name}/check_mk(/.*)?"
# apply to files created by librenms rpm
restorecon -R %{_datadir}/%{name}
restorecon -R %{_localstatedir}/lib/%{name}
restorecon -R %{_localstatedir}/log/%{name}
restorecon -R %{_sysconfdir}/%{name}

# set httpd permissions
getsebool httpd_can_network_connect | grep "> on"  >/dev/null || setsebool -P httpd_can_network_connect on
getsebool httpd_can_sendmail | grep "> on"  >/dev/null || setsebool -P httpd_can_sendmail on
getsebool httpd_execmem | grep "> on"  >/dev/null || setsebool -P httpd_execmem on
getsebool httpd_unified | grep "> on"  >/dev/null || setsebool -P httpd_unified on

# allow fping from http
checkmodule -M -m -o %{_datadir}/%{name}/selinux/http_fping.mod %{_datadir}/%{name}/selinux/http_fping.te
semodule_package -o %{_datadir}/%{name}/selinux/http_fping.pp -m %{_datadir}/%{name}/selinux/http_fping.mod
semodule -i %{_datadir}/%{name}/selinux/http_fping.pp
) &>/dev/null
%endif

%{_bindir}/systemctl condrestart httpd > /dev/null 2>&1 || :

# set file access control lists
setfacl -d -m g::rwx %{_datadir}/%{name}/{bootstrap/cache,rrd,storage,logs}
setfacl -R -m g::rwx %{_datadir}/%{name}/{bootstrap/cache,rrd,storage,logs}

# create librenms php-fpm file if not exist
if [ ! -f %{_sysconfdir}/php-fpm.d/%{name}.conf ]; then
    cp -a %{_sysconfdir}/php-fpm.d/{www,%{name}}.conf
    sed -i -e "s/apache/%{name}/g" %{_sysconfdir}/php-fpm.d/%{name}.conf 
    sed -i -e "s/listen.acl_users = %{name},nginx/listen.acl_users = apache,nginx/g" %{_sysconfdir}/php-fpm.d/%{name}.conf
    sed -i -e "s/www/%{name}/g" %{_sysconfdir}/php-fpm.d/%{name}.conf
    sed -i -e "s/%{name}.foo/www.foo/g" %{_sysconfdir}/php-fpm.d/%{name}.conf
    sed -i -e "s/var\/%{name}/var\/www/g" %{_sysconfdir}/php-fpm.d/%{name}.conf
fi

# install or update and check requirements
for f in %{_localstatedir}/log/%{name}/install_*.log*; do echo $f > /dev/null ; done
if [ ! -f $f ]; then
	echo $'\nSELinux:\n' > %{_localstatedir}/log/%{name}/install_%{version}.log
	getsebool -a | grep httpd | grep "> on" >> %{_localstatedir}/log/%{name}/install_%{version}.log
	echo $'\nValidate:\n' >> %{_localstatedir}/log/%{name}/install_%{version}.log
	su -P - %{name} -c './validate.php' >> %{_localstatedir}/log/%{name}/install_%{version}.log
	chown librenms:librenms %{_localstatedir}/log/%{name}/install_%{version}.log
else
	echo $'\nSELinux:\n' > %{_localstatedir}/log/%{name}/upgrade_%{version}.log
	getsebool -a | grep httpd | grep "> on" >> %{_localstatedir}/log/%{name}/upgrade_%{version}.log
	echo $'\nUpdate:\n' >> %{_localstatedir}/log/%{name}/upgrade_%{version}.log
	su -P - %{name} -c 'lnms update' >> %{_localstatedir}/log/%{name}/upgrade_%{version}.log
	echo $'\nValidate:\n' >> %{_localstatedir}/log/%{name}/upgrade_%{version}.log
	su -P - %{name} -c './validate.php' >> %{_localstatedir}/log/%{name}/upgrade_%{version}.log
	chown librenms:librenms %{_localstatedir}/log/%{name}/upgrade_%{version}.log
fi

# disable librenms rolling updates
su -P - %{name} -c 'lnms config:set update false'

%systemd_post %{name}-scheduler.service
%systemd_post %{name}-scheduler.timer

%preun
%systemd_preun %{name}-scheduler.service
%systemd_preun %{name}-scheduler.timer

%postun
%if %{with_selinux}
if [ "$1" -eq "0" ]; then
    # remove librenms file context
    (
    semanage fcontext -d "%{_datadir}/%{name}(/.*)?"
    semanage fcontext -d "%{_localstatedir}/lib/%{name}/(.cache|.config.local|rrd|storage)(/.*)?"
    semanage fcontext -d "%{_localstatedir}/log/%{name}(/.*)?"
    semanage fcontext -d "%{_sysconfdir}/%{name}(/.*)?"
    ) &>/dev/null
fi
for f in %{_datadir}/%{name}/selinux/http_fping.{mod,pp}
do if [ -f $f ]; then rm $f; fi
done
%endif

%{_bindir}/systemctl condrestart httpd > /dev/null 2>&1 || :


%post rrdcached
%if %{with_selinux}
(
# allow rrdcached for librenms
checkmodule -M -m -o %{_datadir}/%{name}/selinux/rrdcached_librenms.mod %{_datadir}/%{name}/selinux/rrdcached_librenms.te
semodule_package -o %{_datadir}/%{name}/selinux/rrdcached_librenms.pp -m %{_datadir}/%{name}/selinux/rrdcached_librenms.mod
semodule -i %{_datadir}/%{name}/selinux/rrdcached_librenms.pp
) &>/dev/null
%endif

su -P - %{name} -c 'lnms config:set rrdcached "unix:/run/rrdcached.sock"'

%systemd_post rrdcached.service

%preun rrdcached
%systemd_preun rrdcached.service

%postun rrdcached
%if %{with_selinux}
for f in %{_datadir}/%{name}/selinux/rrdcached_librenms.{mod,pp}
do if [ -f $f ]; then rm $f; fi
done
%endif


%post snmptrap
%if %{with_selinux}
(
# allow snmptrap for librenms
checkmodule -M -m -o %{_datadir}/%{name}/selinux/snmptrap_librenms.mod %{_datadir}/%{name}/selinux/snmptrap_librenms.te
semodule_package -o %{_datadir}/%{name}/selinux/snmptrap_librenms.pp -m %{_datadir}/%{name}/selinux/snmptrap_librenms.mod
semodule -i %{_datadir}/%{name}/selinux/snmptrap_librenms.pp
) &>/dev/null
%endif

su -P - %{name} -c 'lnms config:set snmptraps.eventlog "unhandled"'
su -P - %{name} -c 'lnms config:set snmptraps.eventlog_detailed false'

%systemd_post snmptrapd.service

%preun snmptrap
%systemd_preun snmptrapd.service

%postun snmptrap
%if %{with_selinux}
for f in %{_datadir}/%{name}/selinux/snmptrap_librenms.{mod,pp}
do if [ -f $f ]; then rm $f; fi
done
%endif


%post services
su -P - %{name} -c './check-services.php -d' >> %{_localstatedir}/log/%{name}/services_%{version}.log
chown librenms:librenms %{_localstatedir}/log/%{name}/services_%{version}.log
%endif


%post check-mk-agent
%systemd_post check_mk@.service
%systemd_post check_mk.socket

%preun check-mk-agent
%systemd_preun check_mk@.service
%systemd_preun check_mk.socket


%pre snmp-agent
grep "includeDir /etc/snmp/conf.d" %{_sysconfdir}/snmp/snmpd.conf || echo $'\nincludeDir /etc/snmp/conf.d' >> %{_sysconfdir}/snmp/snmpd.conf

%post snmp-agent
%systemd_post snmpd.service
if [ -f "%{_sysconfdir}/snmp/conf.d/%{name}-snmpd.conf" ] ; then
    mv %{_sysconfdir}/snmp/conf.d/%{name}-{snmpd,agent}.conf
fi

%preun snmp-agent
%systemd_preun snmpd.service


%if %{with_monitor}
%post weathermap
%if %{with_selinux}
(
# create librenms-weathermap file context
semanage fcontext -a -s system_u -t httpd_cache_t -r s0 "%{_datadir}/%{name}/html/plugins/Weathermap/output"
semanage fcontext -a -s system_u -t httpd_cache_t -r s0 "%{_localstatedir}/lib/%{name}/output(/.*)?"
# apply to files created by librenms-weathermap rpm
restorecon -R %{_datadir}/%{name}/html/plugins/Weathermap/output
restorecon -R %{_localstatedir}/lib/%{name}/output
) &>/dev/null
%endif

%postun weathermap
%if %{with_selinux}
if [ "$1" -eq "0" ]; then
    # remove librenms-weathermap file context
    (
    semanage fcontext -d "%{_datadir}/%{name}/html/plugins/Weathermap/output"
    semanage fcontext -d "%{_localstatedir}/lib/%{name}/output(/.*)?"
    ) &>/dev/null
fi
%endif
%endif


%if %{with_monitor}
%files -f %{name}.lang
%{!?_licensedir:%global license %%doc}
%doc *.md *.Fedora doc
%license LICENSE.txt licenses

%if %{with_selinux}
%{_datadir}/%{name}/selinux/http_fping.te
%endif

%config(noreplace) %{_sysconfdir}/cron.d/%{name}
%config(noreplace) %{_sysconfdir}/httpd/conf.d/%{name}.conf
%if %{with_nginx}
%config(noreplace) %{_sysconfdir}/nginx/default.d/%{name}.conf
%endif
%ghost %config(noreplace) %{_sysconfdir}/php-fpm.d/%{name}.conf

%{_sysconfdir}/logrotate.d/%{name}

%{_sysconfdir}/bash_completion.d/lnms
%{_bindir}/lnms

%{_unitdir}/%{name}-scheduler.service
%{_unitdir}/%{name}-scheduler.timer

%{_datadir}/%{name}/.env
%{_datadir}/%{name}/config.php
%{_datadir}/%{name}/.cache
%{_datadir}/%{name}/.config
%{_datadir}/%{name}/.local
%{_datadir}/%{name}/config
%{_datadir}/%{name}/bootstrap/cache
%{_datadir}/%{name}/rrd
%{_datadir}/%{name}/storage
%{_datadir}/%{name}/logs

%defattr(-,%{name},%{name},750)
%dir %{_sysconfdir}/%{name}/config
%config(noreplace) %{_sysconfdir}/%{name}/.env
%config(noreplace) %{_sysconfdir}/%{name}/config.php
%config(noreplace) %{_sysconfdir}/%{name}/config/*.php

# python requirements
%{_datadir}/%{name}/requirements.txt
# php requirements
%{_datadir}/%{name}/composer.json
%{_datadir}/%{name}/*.js
%{_datadir}/%{name}/*.php
%{_datadir}/%{name}/*.py
%exclude %{_datadir}/%{name}/services-wrapper.py
%{_datadir}/%{name}/*.sh
%{_datadir}/%{name}/artisan
%{_datadir}/%{name}/cronic
%{_datadir}/%{name}/lnms
%{_datadir}/%{name}/app
%{_datadir}/%{name}/bootstrap/app.php
%{_datadir}/%{name}/database
%{_datadir}/%{name}/html
%exclude %{_datadir}/%{name}/html/plugins/Weathermap
%{_datadir}/%{name}/includes
%{_datadir}/%{name}/LibreNMS
%{_datadir}/%{name}/mibs
%{_datadir}/%{name}/misc
%{_datadir}/%{name}/resources
%{_datadir}/%{name}/routes
%{_datadir}/%{name}/scripts
%{_datadir}/%{name}/tests
%{_datadir}/%{name}/vendor

%dir %{_datadir}/%{name}/lang

# theses folders can contain private information (cache, files, ...)
%attr(750,%{name},%{name}) %{_localstatedir}/lib/%{name}/.cache
%attr(750,%{name},%{name}) %{_localstatedir}/lib/%{name}/.config
%attr(750,%{name},%{name}) %{_localstatedir}/lib/%{name}/.local
%attr(750,%{name},%{name}) %{_localstatedir}/lib/%{name}/cache
%attr(750,%{name},%{name}) %{_localstatedir}/lib/%{name}/storage
%attr(775,%{name},%{name}) %{_localstatedir}/lib/%{name}/rrd

%attr(640,%{name},%{name}) %ghost %config(noreplace,missingok) %{_localstatedir}/log/%{name}/install_%{version}.log
%attr(640,%{name},%{name}) %ghost %config(noreplace,missingok) %{_localstatedir}/log/%{name}/upgrade_%{version}.log
%attr(640,%{name},%{name}) %ghost %config(noreplace,missingok) %{_localstatedir}/log/%{name}/%{name}.log
%endif

 
%files common
%if %{with_selinux}
%attr(0750,root,root) %dir %{_datadir}/%{name}/selinux
%endif

%attr(0755,root,root) %dir %{_libdir}/%{name}
%attr(0755,root,root) %dir %{_libdir}/%{name}/nagios-plugins
%attr(0755,root,root) %dir %{_libdir}/%{name}/check_mk_agent
%attr(0755,root,root) %dir %{_libdir}/%{name}/snmp

%attr(0750,root,%{name}) %dir %{_sysconfdir}/snmp/conf.d

%attr(0750,%{name},%{name}) %dir %{_sysconfdir}/%{name}

%attr(0750,%{name},%{name}) %dir %{_datadir}/%{name}

%attr(0755,%{name},%{name}) %dir %{_localstatedir}/cache/%{name}
%attr(0750,%{name},%{name}) %dir %{_localstatedir}/lib/%{name}
%attr(0750,%{name},%{name}) %dir %{_localstatedir}/log/%{name}


%if %{with_monitor}
%files rrdcached
%if %{with_selinux}
%{_datadir}/%{name}/selinux/rrdcached_librenms.te
%endif

%{_unitdir}/%{name}-rrdcached.service


%files snmptrap
%if %{with_selinux}
%{_datadir}/%{name}/selinux/snmptrap_librenms.te
%endif

%{_unitdir}/%{name}-snmptrapd.service

%attr(660,root,%{name}) %config(noreplace) %{_sysconfdir}/snmp/conf.d/%{name}-trapd.conf

%attr(640,%{name},%{name}) %ghost %config(noreplace,missingok) %{_localstatedir}/log/%{name}/snmptrap.log


%files services
%config(noreplace) %{_sysconfdir}/cron.d/%{name}-services

%defattr(-,%{name},%{name},750)
%config(noreplace) %{_sysconfdir}/%{name}/config-services.php

%ghost %config(noreplace,missingok) %{_localstatedir}/log/%{name}/services_%{version}.log

%{_datadir}/%{name}/services-wrapper.py
%endif


%files check-mk-agent
%doc agent/agent-local/README 

%dir %{_sysconfdir}/%{name}/check_mk
%config(noreplace) %{_sysconfdir}/%{name}/check_mk/mrpe.cfg

%{_bindir}/check_mk_agent
%{_bindir}/mk_enplug

%{_libdir}/%{name}/check_mk_agent/local
%{_libdir}/%{name}/check_mk_agent/plugins
%{_libdir}/%{name}/check_mk_agent/repo

%{_localstatedir}/lib/%{name}/check_mk_agent

%{_unitdir}/check_mk@.service
%{_unitdir}/check_mk.socket


%files snmp-agent
%attr(660,root,%{name}) %config(noreplace) %{_sysconfdir}/snmp/conf.d/%{name}-agent.conf

%{_bindir}/librenms_distro


%files snmp-extend
%attr(660,root,%{name}) %config(noreplace) %{_sysconfdir}/snmp/conf.d/%{name}-extend.conf
%config(noreplace) %{_sysconfdir}/snmp/conf.d/%{name}-extend.conf

%{_bindir}/librenms_return_optimizer

%{_libdir}/%{name}/snmp/*


%if %{with_monitor}
%files weathermap
%doc html/plugins/Weathermap/{CHANGES,COPYING,TODO,*.md,docs}
%license html/plugins/Weathermap/LICENSE

%attr(600,root,root) %config(noreplace) %{_sysconfdir}/cron.d/%{name}-weathermap

%{_datadir}/%{name}/html/plugins/Weathermap/output
%attr(750,%{name},%{name}) %{_localstatedir}/lib/%{name}/output

%defattr(-,%{name},%{name},750)
%dir %{_sysconfdir}/%{name}/config-weathermap
%config(noreplace) %{_sysconfdir}/%{name}/config-weathermap.php
%config(noreplace) %{_sysconfdir}/%{name}/config-weathermap/*.php

%dir %{_datadir}/%{name}/html/plugins/Weathermap
%{_datadir}/%{name}/html/plugins/Weathermap/*.js
%{_datadir}/%{name}/html/plugins/Weathermap/*.php
%{_datadir}/%{name}/html/plugins/Weathermap/images
%{_datadir}/%{name}/html/plugins/Weathermap/lib
%{_datadir}/%{name}/html/plugins/Weathermap/vendor
%{_datadir}/%{name}/html/plugins/Weathermap/editor-resources
%{_datadir}/%{name}/html/plugins/Weathermap/editcache
%endif


%changelog
* Tue Nov 26 2024 Jean-Marc Liger <ligenix@iscp.fr> - 24.11.0~20241121-1
- Update to 24.11.0
  see https://community.librenms.org/t/24-11-0-release-announcement/26569

* Thu Nov 07 2024 Jean-Marc Liger <ligenix@iscp.fr> - 24.10.1~20241107-1
- Update to 24.10.1
  see https://community.librenms.org/t/24-10-0-release-announcement/26462

* Tue Oct 22 2024 Jean-Marc Liger <ligenix@iscp.fr> - 24.9.1~20241022-1
- Fix /usr/lib64/librenms/nagios-plugins scan

* Wed Oct 02 2024 Jean-Marc Liger <ligenix@iscp.fr> - 24.9.1~20240930-1
- Update to 24.9.1
  see https://community.librenms.org/t/24-9-0-release-announcement/26200
- Requires php >= 8.2.0

* Fri Aug 30 2024 Jean-Marc Liger <ligenix@iscp.fr> - 24.8.1~20240829-1
- Update to 24.8.1
  see https://community.librenms.org/t/24-8-0-changelog/25851
- Fix /usr/local/bin
- Fix Binary in grep for EL7 and EL8

* Fri Jul 19 2024 Jean-Marc Liger <ligenix@iscp.fr> - 24.7.0~20240719-1
- Update to 24.7.0
  see https://community.librenms.org/t/24-7-0-changelog/24967

* Fri Jun 21 2024 Jean-Marc Liger <ligenix@iscp.fr> - 24.6.0~20240621-1
- Update to 24.6.0
  see https://community.librenms.org/t/24-6-0-changelog/24707

* Wed May 29 2024 Jean-Marc Liger <ligenix@iscp.fr> - 24.5.0~20240529-1
- Update to 24.5.0
  see https://community.librenms.org/t/24-5-0-changelog/24465

* Thu Apr 25 2024 Jean-Marc Liger <ligenix@iscp.fr> - 24.4.1~20240423-1
- Update to 24.4.1
  see https://community.librenms.org/t/24-4-0-changelog/24157

* Wed Apr 03 2024 Jean-Marc Liger <ligenix@iscp.fr> - 24.3.0~20240402-1
- Update to 24.3.0
  see https://community.librenms.org/t/24-3-0-changelog/24000

* Thu Feb 29 2024 Jean-Marc Liger <ligenix@iscp.fr> - 24.2.0~20240228-1
- Update to 24.2.0
  see https://community.librenms.org/t/24-2-0-release-announcement/23722

* Sat Jan 20 2024 Jean-Marc Liger <ligenix@iscp.fr> - 24.1.0~20240120-1
- Recommend php-ldap
- Recommend php-opache #Félix Bouynot
- Enable snmptrap subpackage #Félix Bouynot
- Move /etc/snmp/conf.d in common subpackage
- Update selinux for librenms-service.py
- Rearrange spec file

* Mon Jan 08 2024 Jean-Marc Liger <ligenix@iscp.fr> - 24.1.0~20240107-1
- Update to 24.1.0
  See https://community.librenms.org/t/24-1-0-release-announcement/23272

* Sat Nov 25 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.11.0~20231124-1
- Add missing artisan

* Sat Nov 18 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.11.0~20231117-1
- Update to 23.10.0
  see https://community.librenms.org/t/23-11-0-release-announcement/22834
- Add subagent configuration to snmp-agent

* Tue Nov 07 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.10.0~20231031-5
- Enable check-mk-agent, snmp-agent, snmp-extend subpackages only
  for EL7 and EL8 narch x86_64
- Rename /etc/snmp/conf.d/librenms-{snmpd,agent}.conf

* Sat Nov 04 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.10.0~20231031-4
- Revert exclude /usr/share/librenms/config.php

* Sat Nov 04 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.10.0~20231031-3
- Enable snmp-agent subpackage
- Missing snmp-extend subpackage Requires
- Fix includeDir /etc/snmp/conf.d

* Fri Nov 03 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.10.0~20231031-2
- Rework weathermap subpackage

* Tue Oct 31 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.10.0~20231031-1
- Update to 23.10.0
  see https://community.librenms.org/t/23-10-0-release-announcement/22646
- Add missing cronic
- Fix command-runner import
- Fix logrotate without error
- Enable rrdcached subpackage

* Mon Oct 09 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.9.1~20231009-1
- Fix some SELinux issues with /var/lib/librenms

* Thu Sep 28 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.9.1~20230927-1
- Fix logrotate
- Fix lang owner

* Sun Sep 24 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.9.1~20230920-1
- Update to 23.9.1
- Fix services config file

* Mon Sep 18 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.9.0~20230915-1
- Update to 23.9.0
  see https://community.librenms.org/t/23-9-0-release-announcement/22321

* Mon Aug 28 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.8.2~20230826-1
- Add /etc/snmp/conf.d repository for librenms.{snmpd,extend}.conf files
- Fix some SELinux issues with logs
- Enable weathermap subpackage

* Sat Aug 26 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.8.2~20230822-2
- Fix services config file

* Thu Aug 24 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.8.2~20230822-1
- Update to 23.8.2
  add PR #15237 and #15238
- Split user, group and directories owner in common subpackage
- Enable services, check-mk-agent, snmp-extend subpackages

* Mon Aug 21 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.8.0~20230820-1
- Update to 23.8.0
  see https://community.librenms.org/t/23-8-0-release-announcement/22082
  drop sql-schema/
- Fix some SELinux issues with python and fping
- Add auto-update post install instructions

* Mon Aug 14 2023 Jean-Marc Liger <ligenix@iscp.fr> - 23.7.0~20230814-1
- Initial RPM 23.7.0
  see https://community.librenms.org/t/23-7-0-changelog/21841