#!/bin/bash
#
# Thanks to useful information on the Internet:
# https://wiki.debian.org/Icinga/Icinga2Installation
# https://www.linode.com/docs/uptime/monitoring/install-icinga2-monitoring-on-debian-9/
#
# Author/Copyright:	Wolfgang Schweer <wschweer@arcor.de>
# Licence:			GPL2+
# first edited:		2020-03-23
# last edited:		2021-08-16
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

set -e

. /usr/share/debconf/confmodule

db_get debian-edu-config/first-user-name
FIRSTUSERNAME="$RET"

# Secure the MariaDB installation, see the first four mysql commands in the
# setup_icinga function. Also, the automatically generated initial database
# 'icinga2' will be removed at the end of the function.
# TODO: Set mysql root password after first reboot of a main server.
# (Add instruction to the manual's 'Getting started' chapter, i.e.
# run 'mysql_secure_installation'.)

setup_icinga() {
	# Generate random password (alphanumeric ASCII characters only in order
	# to avoid problems with quoting below)
	password="$(LC_ALL=C tr -cd '[:alnum:]' < /dev/urandom | dd bs=1 count=16 2>/dev/null)"
	[ -n "${password}" ] || exit 1

	# Delete anonymous users
	mysql -e "DELETE FROM mysql.user WHERE User='';"
	# Ensure the root user can not log in remotely
	mysql -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');"
	# Remove the test database
	mysql -e "DROP DATABASE IF EXISTS test;"
	mysql -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\_%';"
	# Make the changes take effect
	mysql -e "FLUSH PRIVILEGES"

	# Enable command feature and modules
	icinga2 feature enable command
	icingacli module enable monitoring

	# Create the Icinga 2 application database with all privileges for the first user

	mysql <<< "
	CREATE DATABASE icingadb;
	GRANT SELECT, INSERT, UPDATE, DELETE, DROP, CREATE VIEW, INDEX, EXECUTE
	ON icingadb.*
	TO 'icinga2'@'localhost'
	IDENTIFIED BY '${password}';
	FLUSH PRIVILEGES;
	"
	# Install the MySQL schema required for the Icinga 2 database
	mysql icingadb < /usr/share/icinga2-ido-mysql/schema/mysql.sql

	# Adjust the Icinga 2 MySQL IDO configuration
	#sed -i "/user/ s%icinga2%$FIRSTUSERNAME%" "/etc/icinga2/features-available/ido-mysql.conf"
	sed -i "/password/s/.*/  password = \"${password}\",/" /etc/icinga2/features-available/ido-mysql.conf
	sed -i '/database/ s%icinga2%icingadb%' /etc/icinga2/features-available/ido-mysql.conf

	# Enable ido-mysql feature
	icinga2 feature enable ido-mysql

	# Create Icinga Web 2 database
	mysql <<< "
	CREATE DATABASE icingaweb2;
	GRANT SELECT, INSERT, UPDATE, DELETE, DROP, CREATE VIEW, INDEX, EXECUTE
	ON icingaweb2.*
	TO 'icingaweb2'@'localhost'
	IDENTIFIED BY '${password}';
	FLUSH PRIVILEGES;
	"
	# Install the MySQL schema required for the Icinga Web 2 database
	mysql icingaweb2 < /usr/share/icingaweb2/schema/mysql.schema.sql

	# Add icinga2 configuration files (content gathered from manual setup procedure)
	#
	# authentication.ini
	cat <<- EOF > /etc/icingaweb2/authentication.ini
	[icingaweb2]
	user_class = "inetOrgPerson"
	filter = ""
	user_name_attribute = "uid"
	backend = "ldap"
	base_dn = "dc=skole,dc=skolelinux,dc=no"
	domain = ""
	resource = "icingaweb_ldap"
	EOF

	# config.ini
	cat <<- EOF > /etc/icingaweb2/config.ini
	[global]
	show_stacktraces = "1"
	show_application_state_messages = "1"
	config_resource = "icingaweb_db"

	[logging]
	log = "file"
	level = "ERROR"
	file = "/var/log/icingaweb2/icingaweb2.log"
	EOF

	# groups.ini
	cat <<- EOF > /etc/icingaweb2/groups.ini
	[icingaweb2]
	resource = "icingaweb_ldap"
	user_backend = "icingaweb2"
	group_class = "posixGroup"
	group_filter = ""
	group_name_attribute = "cn"
	group_member_attribute = "memberUid"
	base_dn = "dc=skole,dc=skolelinux,dc=no"
	backend = "ldap"
	EOF

	# roles.ini
	cat <<- EOF > /etc/icingaweb2/roles.ini
	[Administrators]
	groups = "icinga-admins"
	permissions = "*"
	EOF

	# resources.ini
	cat <<- EOF > /etc/icingaweb2/resources.ini
	[icingaweb_ldap]
	type = "ldap"
	hostname = "tjener.intern"
	port = "389"
	encryption = "starttls"
	root_dn = "dc=skole,dc=skolelinux,dc=no"
	bind_dn = ""
	bind_pw = ""
	timeout = "5"

	[icingaweb_db]
	type = "db"
	db = "mysql"
	host = "localhost"
	port = ""
	dbname = "icingaweb2"
	username = "icingaweb2"
	password = "${password}"
	charset = ""
	use_ssl = "0"

	[icinga_ido]
	type = "db"
	db = "mysql"
	host = "localhost"
	port = ""
	dbname = "icingadb"
	username = "icinga2"
	password = "${password}"
	charset = ""
	use_ssl = "0"
	EOF

	# Add icingaweb2 configuration files (content gathered from manual setup procedure)
	#
	# Just in case the directory is still missing
	mkdir -p /etc/icingaweb2/modules/monitoring/

	# config.ini
	cat <<- EOF > /etc/icingaweb2/modules/monitoring/config.ini
	[security]
	protected_customvars = "*pw*,*pass*,community"
	EOF

	# commandtransports.ini
	cat <<- EOF > /etc/icingaweb2/modules/monitoring/commandtransports.ini
	[icinga2]
	transport = "local"
	path = "/var/run/icinga2/cmd/icinga2.cmd"
	EOF

	# backends.ini
	cat <<- EOF > /etc/icingaweb2/modules/monitoring/backends.ini
	[icinga]
	type = "ido"
	resource = "icinga_ido"
	EOF

	# Adjusts rights to get the web interface working
	find /etc/icingaweb2/ -type f -name '*.ini' -exec chmod 660 {} +
	find /etc/icingaweb2/ -type d -exec chmod 775 {} +

	# Create icingaweb2 log directory
	mkdir -p /var/log/icingaweb2/
	chgrp -R icingaweb2 /var/log/icingaweb2/
	chmod -R 775 /var/log/icingaweb2/

	# Remove now obsoleted initial database
	mysql -e "DROP DATABASE IF EXISTS icinga2;"
	mysql -e "DELETE FROM mysql.db WHERE Db='icinga2' OR Db='icinga2\_%';"
	mysql -e "FLUSH PRIVILEGES"
}

## Make sure the MariaDB server is running.
PID=$(pidof mariadbd || /bin/true)
if [ -z "$PID" ]; then
	echo "The MariaDB server doesn't seem to be running. Trying to start it." 1>&2
	if [ -x /sbin/start-stop-daemon.REAL ] ; then
		## we need this to start MariaDB server during installation
		mv /sbin/start-stop-daemon /sbin/start-stop-daemon.FAKE
		cp /sbin/start-stop-daemon.REAL /sbin/start-stop-daemon
	fi
	service mariadb start
	mariadb_started=true
fi

PID=$(pidof mariadbd || /bin/true)
if [ -z "$PID" ]; then
	echo "error: the MariaDB server is not running. Skipping Icinga 2 setup." 1>&2
	exit 1
else
	setup_icinga || echo "error: unable to set up Icinga 2."
fi

if [ true = "$mariadb_started" ] ; then
	service mariadb stop
	if [ -x /sbin/start-stop-daemon.REAL ] ; then
		mv /sbin/start-stop-daemon.FAKE /sbin/start-stop-daemon
    fi
fi
