#! /bin/bash
# Parallel Icinga instance on MLS level sN (paths *-sN). Roles: master | agent.
# Does not modify the s0 stack.

VER="1.1.0"
PROG=$(basename "$0")

ICINGA2_BIN=/usr/lib64/icinga2/sbin/icinga2

MLS_NUM=
ROLE=master
SHOW_INFO=
DO_REMOVE=
DO_START=
SKIP_API_SETUP=
API_PORT=
WEB_PORT=
PG_PORT=
PG_SOCKET=
PHP_VER=
DB_USER=icinga
DB_PASS=
NODENAME=
ZONENAME=
SHARE=
ENDPOINT_BODY=
TICKET_SALT=

usage() {
	cat <<EOF
Usage: $PROG -l|--level={1,2,3} [--role=master|agent] [options]

  -l, --level=N              MLS level 1|2|3
      --role=master|agent    default: master
                               master: icinga2, php-fpm, nginx, director, web
                               agent:  icinga2 only
  -i, --info
      --api-port=PORT        default: 5665+N
      --web-port=PORT        default: 80+N (master)
      --pg-port=PORT         default: 5434+N (master)
      --pg-socket=DIR        default: /ptmp/sN
      --php-ver=X.Y          default: autodetect / 8.5
      --db-user=NAME         default: icinga
      --db-pass=PASS         IDO password (default: CHANGEME)
      --nodename=NAME        default: hostname -s
      --zonename=NAME        default: nodename
      --start                systemctl enable --now
      --skip-api-setup       skip api setup (master)
  -r, --remove               remove *-sN artifacts for this role
  -h, --help
EOF
	exit "${1:-0}"
}

die() { echo "$PROG: $*" >&2; exit 1; }
need_root() { [ "$(id -u)" -eq 0 ] || die "root required"; }
is_master() { [ "$ROLE" = master ]; }
is_agent() { [ "$ROLE" = agent ]; }

SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
# Parent of sbin/: project tree or install prefix (/usr when in /usr/sbin).
PREFIX=$(cd "$SCRIPT_DIR/.." && pwd)

find_share() {
	local d
	for d in \
		"$PREFIX/share/icinga-mls-setup" \
		/usr/share/icinga-mls-setup
	do
		[ -d "$d/templates" ] && { echo "$d"; return 0; }
	done
	return 1
}

set_endpoint_body() {
	if is_master; then
		ENDPOINT_BODY=$(printf '  host = "127.0.0.1"\n  port = "%s"\n' "$API_PORT")
	else
		ENDPOINT_BODY=""
	fi
}

render() {
	local tmp bodyf
	tmp=$(mktemp)
	bodyf=$(mktemp)
	printf '%s' "$ENDPOINT_BODY" > "$bodyf"
	sed \
		-e "s|_MLS_NUM_|${MLS_NUM}|g" \
		-e "s|_PHPVER_|${PHP_VER}|g" \
		-e "s|WEBPORT|${WEB_PORT}|g" \
		-e "s|_APICPORT_|${API_PORT}|g" \
		-e "s|_DBUSER_|${DB_USER}|g" \
		-e "s|_DBPASS_|${DB_PASS}|g" \
		-e "s|_PGHOST_|${PG_SOCKET}|g" \
		-e "s|_PGPORT_|${PG_PORT}|g" \
		-e "s|_NODENAME_|${NODENAME}|g" \
		-e "s|_ZONENAME_|${ZONENAME}|g" \
		-e "s|_TICKET_SALT_|${TICKET_SALT}|g" \
		> "$tmp"
	awk -v bf="$bodyf" '
		index($0, "_ENDPOINT_BODY_") {
			while ((getline line < bf) > 0) print line
			close(bf)
			next
		}
		{ print }
	' "$tmp"
	rm -f "$tmp" "$bodyf"
}

install_from_template() {
	local src=$1 dest=$2
	[ -f "$src" ] || die "missing template: $src"
	mkdir -p "$(dirname "$dest")"
	render < "$src" > "$dest"
	echo "  + $dest"
}

mls_label() { echo "s${MLS_NUM}-s${MLS_NUM}"; }

chcon_def() {
	local p
	for p in "$@"; do
		[ -e "$p" ] || continue
		chcon -R -u generic_u -r object_r -t def_t -l "$(mls_label)" "$p" 2>/dev/null \
			|| chcon -R -l "$(mls_label)" "$p" || true
	done
}

detect_php_ver() {
	local u
	u=$(systemctl list-unit-files 'php*-fpm.service' --no-legend 2>/dev/null | awk '{print $1}' | head -1)
	if [[ "$u" =~ php([0-9]+\.[0-9]+)-fpm ]]; then
		echo "${BASH_REMATCH[1]}"
		return 0
	fi
	if command -v php >/dev/null 2>&1; then
		php -r 'echo PHP_MAJOR_VERSION.".".PHP_MINOR_VERSION;' 2>/dev/null && return 0
	fi
	echo "8.5"
}

gen_salt() {
	if command -v openssl >/dev/null 2>&1; then
		openssl rand -base64 32 | tr -d '/+=' | head -c 40
	else
		tr -dc 'A-Za-z0-9' </dev/urandom | head -c 40
	fi
}

icinga2_sN() {
	local subcmd=$1
	shift
	"$ICINGA2_BIN" "$subcmd" "$@" \
		-DConfigDir="/etc/icinga2-s${MLS_NUM}" \
		-DDataDir="/var/lib/icinga2-s${MLS_NUM}" \
		-DZonesDir="/etc/icinga2-s${MLS_NUM}/zones.d" \
		-DLogDir="/var/log/icinga2-s${MLS_NUM}" \
		-DCacheDir="/var/cache/icinga2-s${MLS_NUM}" \
		-DInitRunDir="/run/icinga2-s${MLS_NUM}" \
		-DPidPath="/run/icinga2-s${MLS_NUM}/icinga2.pid" \
		-DStatePath="/var/lib/icinga2-s${MLS_NUM}/icinga2.state"
}

print_info() {
	cat <<EOF
	role=${ROLE}
	level=s${MLS_NUM}		MLS=$(mls_label)
	api_port=${API_PORT}
	nodename=${NODENAME}		zonename=${ZONENAME}
	icinga2_bin=${ICINGA2_BIN}
	unit: icinga2-mls-s${MLS_NUM}.service
	paths: /etc/icinga2-s${MLS_NUM}  /var/lib/icinga2-s${MLS_NUM}
EOF
	if is_master; then
		cat <<EOF
	web_port=${WEB_PORT}		pg=${PG_SOCKET}:${PG_PORT}
	php_ver=${PHP_VER}
	units: php${PHP_VER}-fpm-mls-s${MLS_NUM} nginx-mls-s${MLS_NUM} icinga-director-mls-s${MLS_NUM}
	web_url=http://$(hostname -f 2>/dev/null || hostname):${WEB_PORT}/icingaweb2/setup
	requires: postgresql-mls-s${MLS_NUM}
EOF
	fi
}

do_remove() {
	echo "==> disable units s${MLS_NUM} (${ROLE})"
	systemctl disable --now "icinga2-mls-s${MLS_NUM}.service" 2>/dev/null || true
	if is_master; then
		systemctl disable --now \
			"php${PHP_VER}-fpm-mls-s${MLS_NUM}.service" \
			"nginx-mls-s${MLS_NUM}.service" \
			"icinga-director-mls-s${MLS_NUM}.service" 2>/dev/null || true
	fi

	rm -f \
		"/etc/systemd/system/icinga2-mls-s${MLS_NUM}.service" \
		"/etc/sysconfig/icinga2-s${MLS_NUM}"
	if is_master; then
		rm -f \
			"/etc/systemd/system/php${PHP_VER}-fpm-mls-s${MLS_NUM}.service" \
			"/usr/lib/systemd/system/php${PHP_VER}-fpm-mls-s${MLS_NUM}.service" \
			"/etc/systemd/system/nginx-mls-s${MLS_NUM}.service" \
			"/etc/systemd/system/icinga-director-mls-s${MLS_NUM}.service" \
			"/etc/sysconfig/icinga-director-s${MLS_NUM}"
	fi
	systemctl daemon-reload

	echo "==> remove *-s${MLS_NUM}"
	rm -rf \
		"/etc/icinga2-s${MLS_NUM}" \
		"/var/lib/icinga2-s${MLS_NUM}" \
		"/var/log/icinga2-s${MLS_NUM}" \
		"/var/cache/icinga2-s${MLS_NUM}" \
		"/run/icinga2-s${MLS_NUM}"

	if is_master; then
		rm -rf \
			"/etc/icingaweb2-s${MLS_NUM}" \
			"/etc/nginx-s${MLS_NUM}" \
			"/etc/fpm${PHP_VER}-s${MLS_NUM}" \
			"/var/lib/icingaweb2-s${MLS_NUM}" \
			"/var/log/nginx-s${MLS_NUM}" \
			"/var/spool/nginx-s${MLS_NUM}" \
			"/var/log/php${PHP_VER}-fpm-s${MLS_NUM}" \
			"/var/log/icingaweb2-s${MLS_NUM}" \
			"/var/www/vhosts/icingaweb2-s${MLS_NUM}" \
			"/run/nginx-s${MLS_NUM}" \
			"/run/php${PHP_VER}-fpm-s${MLS_NUM}" \
			"/run/icingaweb2-s${MLS_NUM}"
		rm -f \
			"/etc/nginx/nginx-s${MLS_NUM}.conf" \
			"/etc/nginx/icingaweb2-s${MLS_NUM}.conf" \
			"/etc/fpm${PHP_VER}/php-fpm-s${MLS_NUM}.conf" \
			"/etc/fpm${PHP_VER}/icingaweb2-s${MLS_NUM}.conf"
	fi
}

prep_dirs_icinga2() {
	mkdir -p \
		"/etc/icinga2-s${MLS_NUM}" \
		"/var/lib/icinga2-s${MLS_NUM}/certs" \
		"/var/log/icinga2-s${MLS_NUM}" \
		"/var/cache/icinga2-s${MLS_NUM}" \
		"/run/icinga2-s${MLS_NUM}"
	chown -R icinga:icinga \
		"/etc/icinga2-s${MLS_NUM}" \
		"/var/lib/icinga2-s${MLS_NUM}" \
		"/var/log/icinga2-s${MLS_NUM}" \
		"/var/cache/icinga2-s${MLS_NUM}" \
		"/run/icinga2-s${MLS_NUM}"
	chcon_def \
		"/etc/icinga2-s${MLS_NUM}" \
		"/var/lib/icinga2-s${MLS_NUM}" \
		"/var/log/icinga2-s${MLS_NUM}" \
		"/var/cache/icinga2-s${MLS_NUM}" \
		"/run/icinga2-s${MLS_NUM}"
}

prep_dirs_web() {
	mkdir -p \
		"/var/lib/icingaweb2-s${MLS_NUM}" \
		"/var/log/icingaweb2-s${MLS_NUM}" \
		"/var/www/vhosts/icingaweb2-s${MLS_NUM}/sessions" \
		"/var/www/vhosts/icingaweb2-s${MLS_NUM}/tmp" \
		"/run/icingaweb2-s${MLS_NUM}" \
		"/run/php${PHP_VER}-fpm-s${MLS_NUM}" \
		"/var/log/php${PHP_VER}-fpm-s${MLS_NUM}" \
		"/etc/fpm${PHP_VER}" \
		"/etc/nginx" \
		"/var/log/nginx-s${MLS_NUM}" \
		"/run/nginx-s${MLS_NUM}" \
		"/var/spool/nginx-s${MLS_NUM}/tmp/proxy" \
		"/var/spool/nginx-s${MLS_NUM}/tmp/fastcgi" \
		"/var/spool/nginx-s${MLS_NUM}/tmp/client" \
		"/var/spool/nginx-s${MLS_NUM}/tmp/uwsgi" \
		"/var/spool/nginx-s${MLS_NUM}/tmp/scgi"

	touch "/var/log/nginx-s${MLS_NUM}/error.log" "/var/log/nginx-s${MLS_NUM}/access.log"

	chown -R icinga:icingaweb2 \
		"/var/www/vhosts/icingaweb2-s${MLS_NUM}" \
		"/run/icingaweb2-s${MLS_NUM}" \
		"/var/log/icingaweb2-s${MLS_NUM}"
	chown icingadirector:icingaweb2 "/var/lib/icingaweb2-s${MLS_NUM}" 2>/dev/null \
		|| chown icinga:icingaweb2 "/var/lib/icingaweb2-s${MLS_NUM}"
	chmod 2770 "/var/lib/icingaweb2-s${MLS_NUM}"
	usermod -a -G icingaweb2 icinga 2>/dev/null || true

	if getent passwd _nginx >/dev/null; then
		chown -R _nginx:_nginx \
			"/var/log/nginx-s${MLS_NUM}" \
			"/run/nginx-s${MLS_NUM}" \
			"/var/spool/nginx-s${MLS_NUM}"
	fi

	chcon_def \
		"/var/lib/icingaweb2-s${MLS_NUM}" \
		"/var/log/icingaweb2-s${MLS_NUM}" \
		"/var/www/vhosts/icingaweb2-s${MLS_NUM}" \
		"/run/icingaweb2-s${MLS_NUM}" \
		"/run/php${PHP_VER}-fpm-s${MLS_NUM}" \
		"/var/log/php${PHP_VER}-fpm-s${MLS_NUM}" \
		"/var/log/nginx-s${MLS_NUM}" \
		"/run/nginx-s${MLS_NUM}" \
		"/var/spool/nginx-s${MLS_NUM}"
}

prep_dirs() {
	echo "==> dirs (${ROLE})"
	prep_dirs_icinga2
	is_master && prep_dirs_web
}

# Write NodeName/ZoneName/TicketSalt. If $2=preserve, keep existing TicketSalt on dest.
patch_constants() {
	local dest=$1
	local mode=${2:-fresh}
	local existing_salt=

	if [ ! -f "$dest/constants.conf" ]; then
		touch "$dest/constants.conf"
	fi

	if [ "$mode" = preserve ]; then
		existing_salt=$(sed -n 's/^const TicketSalt = "\(.*\)".*/\1/p' "$dest/constants.conf" | head -1)
		[ -n "$existing_salt" ] && TICKET_SALT=$existing_salt
	fi

	grep -q "^const NodeName" "$dest/constants.conf" 2>/dev/null \
		&& sed -i "s|^const NodeName.*|const NodeName = \"${NODENAME}\"|" "$dest/constants.conf" \
		|| echo "const NodeName = \"${NODENAME}\"" >> "$dest/constants.conf"
	grep -q "^const ZoneName" "$dest/constants.conf" 2>/dev/null \
		&& sed -i "s|^const ZoneName.*|const ZoneName = \"${ZONENAME}\"|" "$dest/constants.conf" \
		|| echo "const ZoneName = \"${ZONENAME}\"" >> "$dest/constants.conf"

	if is_master; then
		[ -n "$TICKET_SALT" ] || TICKET_SALT=$(gen_salt)
		if grep -q "^const TicketSalt" "$dest/constants.conf" 2>/dev/null; then
			sed -i "s|^const TicketSalt.*|const TicketSalt = \"${TICKET_SALT}\"|" "$dest/constants.conf"
		else
			echo "const TicketSalt = \"${TICKET_SALT}\"" >> "$dest/constants.conf"
		fi
	else
		if grep -q "^const TicketSalt" "$dest/constants.conf" 2>/dev/null; then
			sed -i 's|^const TicketSalt.*|const TicketSalt = ""|' "$dest/constants.conf"
		else
			echo 'const TicketSalt = ""' >> "$dest/constants.conf"
		fi
		TICKET_SALT=
	fi

	if is_master; then
		TICKET_SALT=$(sed -n 's/^const TicketSalt = "\(.*\)".*/\1/p' "$dest/constants.conf" | head -1)
		[ -n "$TICKET_SALT" ] || die "empty TicketSalt"
	fi
}

sanitize_seeded_tree() {
	local dest=$1
	local features=$2
	local f

	# Drop s0 site objects; keep package features-available only.
	rm -rf "$dest/conf.d" "$dest/zones.d"
	mkdir -p "$dest/conf.d" "$dest/zones.d" "$dest/features-available" "$dest/features-enabled"
	rm -f "$dest/features-enabled"/*

	for f in $features; do
		[ -f "$dest/features-available/$f.conf" ] \
			&& ln -sfn "../features-available/$f.conf" "$dest/features-enabled/$f.conf"
	done
}

seed_icinga2_tree() {
	local dest="/etc/icinga2-s${MLS_NUM}"
	local features="checker mainlog"
	local const_mode=fresh

	is_master && features="checker mainlog notification"

	if [ -f "$dest/icinga2.conf" ]; then
		echo "==> keep existing /etc/icinga2-s${MLS_NUM}"
		const_mode=preserve
	else
		echo "==> seed /etc/icinga2-s${MLS_NUM} from /etc/icinga2"
		[ -f /etc/icinga2/icinga2.conf ] || die "icinga2 not installed (/etc/icinga2 missing)"
		cp -a /etc/icinga2/. "$dest/"
		sanitize_seeded_tree "$dest" "$features"
	fi

	patch_constants "$dest" "$const_mode"
	set_endpoint_body

	install_from_template "$SHARE/templates/zones.conf.in" "$dest/zones.conf"
	install_from_template "$SHARE/templates/api.conf.in" "$dest/features-available/api.conf"
	# master: api now. agent: like guide 1.1.2 — checker/mainlog only; api after ticket/register
	if is_master; then
		ln -sfn ../features-available/api.conf "$dest/features-enabled/api.conf"
		install_from_template "$SHARE/templates/ido-pgsql.conf.in" \
			"$dest/features-available/ido-pgsql.conf"
	else
		rm -f "$dest/features-enabled/api.conf"
	fi

	chown -R icinga:icinga "$dest"
	chcon_def "$dest"
}

agent_certs_ready() {
	local certs="/var/lib/icinga2-s${MLS_NUM}/certs"
	[ -f "$certs/${NODENAME}.crt" ] && [ -f "$certs/${NODENAME}.key" ] && [ -f "$certs/ca.crt" ]
}

install_units_icinga2() {
	local T="$SHARE/templates"
	install_from_template "$T/sysconfig-icinga2.in" "/etc/sysconfig/icinga2-s${MLS_NUM}"
	install_from_template "$T/icinga2-mls.service.in" \
		"/etc/systemd/system/icinga2-mls-s${MLS_NUM}.service"
}

install_units_web() {
	local T="$SHARE/templates"
	install_from_template "$T/php-fpm-mls.service.in" \
		"/etc/systemd/system/php${PHP_VER}-fpm-mls-s${MLS_NUM}.service"
	install_from_template "$T/nginx-mls.service.in" \
		"/etc/systemd/system/nginx-mls-s${MLS_NUM}.service"
	install_from_template "$T/icinga-director-mls.service.in" \
		"/etc/systemd/system/icinga-director-mls-s${MLS_NUM}.service"

	install_from_template "$T/php-fpm.conf.in" "/etc/fpm${PHP_VER}/php-fpm-s${MLS_NUM}.conf"
	install_from_template "$T/php-fpm-pool-icingaweb2.conf.in" \
		"/etc/fpm${PHP_VER}/icingaweb2-s${MLS_NUM}.conf"
	install_from_template "$T/nginx-sN.conf.in" "/etc/nginx/nginx-s${MLS_NUM}.conf"
	install_from_template "$T/nginx-icingaweb2-sN.conf.in" \
		"/etc/nginx/icingaweb2-s${MLS_NUM}.conf"

	chcon_def \
		"/etc/fpm${PHP_VER}/php-fpm-s${MLS_NUM}.conf" \
		"/etc/fpm${PHP_VER}/icingaweb2-s${MLS_NUM}.conf" \
		"/etc/nginx/nginx-s${MLS_NUM}.conf" \
		"/etc/nginx/icingaweb2-s${MLS_NUM}.conf"

	cat > "/etc/sysconfig/icinga-director-s${MLS_NUM}" <<EOF
# icinga-director MLS s${MLS_NUM}
EOF
}

install_units_and_configs() {
	echo "==> units (${ROLE})"
	install_units_icinga2
	is_master && install_units_web
	systemctl daemon-reload
}

setup_web_directory() {
	echo "==> icingacli setup config directory"
	export ICINGAWEB_CONFIGDIR="/etc/icingaweb2-s${MLS_NUM}"
	export ICINGAWEB_STORAGEDIR="/var/lib/icingaweb2-s${MLS_NUM}"

	mkdir -p "$ICINGAWEB_STORAGEDIR"
	icingacli setup config directory --group icingaweb2
	icingacli setup token create >/dev/null || true

	chown -R icinga:icingaweb2 "$ICINGAWEB_CONFIGDIR"
	chmod 2770 "$ICINGAWEB_CONFIGDIR"
	chown icingadirector:icingaweb2 "$ICINGAWEB_STORAGEDIR" 2>/dev/null \
		|| chown icinga:icingaweb2 "$ICINGAWEB_STORAGEDIR"
	chmod 2770 "$ICINGAWEB_STORAGEDIR"
	chcon_def "$ICINGAWEB_CONFIGDIR" "$ICINGAWEB_STORAGEDIR"
}

setup_api_master() {
	echo "==> api setup / ido-pgsql"
	[ -x "$ICINGA2_BIN" ] || die "missing $ICINGA2_BIN"

	icinga2_sN api setup

	set_endpoint_body
	install_from_template "$SHARE/templates/api.conf.in" \
		"/etc/icinga2-s${MLS_NUM}/features-available/api.conf"
	ln -sfn ../features-available/api.conf \
		"/etc/icinga2-s${MLS_NUM}/features-enabled/api.conf"
	install_from_template "$SHARE/templates/zones.conf.in" \
		"/etc/icinga2-s${MLS_NUM}/zones.conf"

	install_from_template "$SHARE/templates/ido-pgsql.conf.in" \
		"/etc/icinga2-s${MLS_NUM}/features-available/ido-pgsql.conf"
	icinga2_sN feature enable ido-pgsql 2>/dev/null \
		|| ln -sfn ../features-available/ido-pgsql.conf \
			"/etc/icinga2-s${MLS_NUM}/features-enabled/ido-pgsql.conf"

	chown -R icinga:icinga "/etc/icinga2-s${MLS_NUM}" "/var/lib/icinga2-s${MLS_NUM}"
	chcon_def "/etc/icinga2-s${MLS_NUM}" "/var/lib/icinga2-s${MLS_NUM}"
}

start_services() {
	# agent: start minimal (checker/mainlog). enable api only if certs already present
	# (after icinga2-register-host / ticket enrollment)
	if is_agent; then
		if agent_certs_ready; then
			ln -sfn ../features-available/api.conf \
				"/etc/icinga2-s${MLS_NUM}/features-enabled/api.conf"
		else
			rm -f "/etc/icinga2-s${MLS_NUM}/features-enabled/api.conf"
		fi
		chown -R icinga:icinga "/etc/icinga2-s${MLS_NUM}"
		chcon_def "/etc/icinga2-s${MLS_NUM}"
	fi
	echo "==> enable --now (${ROLE})"
	systemctl enable --now "icinga2-mls-s${MLS_NUM}.service"
	if is_master; then
		systemctl enable --now \
			"php${PHP_VER}-fpm-mls-s${MLS_NUM}.service" \
			"nginx-mls-s${MLS_NUM}.service"
		systemctl disable --now "icinga-director-mls-s${MLS_NUM}.service" 2>/dev/null || true
		echo "  after wizard: systemctl enable --now icinga-director-mls-s${MLS_NUM}"
	fi
}

print_summary() {
	local host
	host=$(hostname -f 2>/dev/null || hostname)

	if is_agent; then
		cat <<EOF

s${MLS_NUM} agent ready (minimal: checker/mainlog)
  unit  icinga2-mls-s${MLS_NUM}.service
  conf  /etc/icinga2-s${MLS_NUM}
  data  /var/lib/icinga2-s${MLS_NUM}
  next  register to master (ticket) — api/certs then
EOF
		return
	fi

	local token api_pass
	export ICINGAWEB_CONFIGDIR="/etc/icingaweb2-s${MLS_NUM}"
	export ICINGAWEB_STORAGEDIR="/var/lib/icingaweb2-s${MLS_NUM}"
	token=$(icingacli setup token show 2>/dev/null || cat "/etc/icingaweb2-s${MLS_NUM}/setup.token" 2>/dev/null || echo "(none)")
	api_pass=$(sed -n 's/.*password = "\([^"]*\)".*/\1/p' \
		"/etc/icinga2-s${MLS_NUM}/conf.d/api-users.conf" 2>/dev/null | head -1)

	cat <<EOF

s${MLS_NUM} master ready
  url        http://${host}:${WEB_PORT}/icingaweb2/setup
  token      ${token}
  api        https://127.0.0.1:${API_PORT}  (root / ${api_pass:-api-users.conf})
  kickstart  127.0.0.1:${API_PORT}
  pg         ${PG_SOCKET}:${PG_PORT}
  director   systemctl enable --now icinga-director-mls-s${MLS_NUM}
EOF
}

# --- args ---
TEMP=$(getopt -n "$PROG" -o l:irh \
	-l level:,role:,info,remove,help,start,skip-api-setup,api-port:,web-port:,pg-port:,pg-socket:,php-ver:,db-user:,db-pass:,nodename:,zonename: -- "$@") || usage 1
eval set -- "$TEMP"
while true; do
	case "$1" in
		-l|--level) MLS_NUM=$2; shift 2 ;;
		--role) ROLE=$2; shift 2 ;;
		-i|--info) SHOW_INFO=1; shift ;;
		-r|--remove) DO_REMOVE=1; shift ;;
		--start) DO_START=1; shift ;;
		--skip-api-setup) SKIP_API_SETUP=1; shift ;;
		--api-port) API_PORT=$2; shift 2 ;;
		--web-port) WEB_PORT=$2; shift 2 ;;
		--pg-port) PG_PORT=$2; shift 2 ;;
		--pg-socket) PG_SOCKET=$2; shift 2 ;;
		--php-ver) PHP_VER=$2; shift 2 ;;
		--db-user) DB_USER=$2; shift 2 ;;
		--db-pass) DB_PASS=$2; shift 2 ;;
		--nodename) NODENAME=$2; shift 2 ;;
		--zonename) ZONENAME=$2; shift 2 ;;
		-h|--help) usage 0 ;;
		--) shift; break ;;
		*) usage 1 ;;
	esac
done

[ -n "$MLS_NUM" ] || usage 0
case "$MLS_NUM" in 1|2|3) ;; *) die "level 1|2|3" ;; esac
case "$ROLE" in master|agent) ;; *) die "--role=master|agent" ;; esac

[ -z "$API_PORT" ] && API_PORT=$((5665 + MLS_NUM))
[ -z "$WEB_PORT" ] && WEB_PORT=$((80 + MLS_NUM))
[ -z "$PG_PORT" ] && PG_PORT=$((5434 + MLS_NUM))
[ -z "$PG_SOCKET" ] && PG_SOCKET="/ptmp/s${MLS_NUM}"
[ -z "$PHP_VER" ] && PHP_VER=$(detect_php_ver)
[ -z "$DB_PASS" ] && DB_PASS=CHANGEME
[ -z "$NODENAME" ] && NODENAME=$(hostname -s)
[ -z "$ZONENAME" ] && ZONENAME=$NODENAME
TICKET_SALT=$(gen_salt)
set_endpoint_body

SHARE=$(find_share) || die "share/icinga-mls-setup not found"

if [ -n "$SHOW_INFO" ]; then
	print_info
	exit 0
fi

need_root

if [ -n "$DO_REMOVE" ]; then
	do_remove
	exit 0
fi

if is_master; then
	if ! systemctl cat "postgresql-mls-s${MLS_NUM}.service" >/dev/null 2>&1; then
		echo "WARNING: postgresql-mls-s${MLS_NUM}.service not found" >&2
	fi
fi

prep_dirs
seed_icinga2_tree
install_units_and_configs

if is_master; then
	if [ -z "$SKIP_API_SETUP" ]; then
		setup_web_directory
		setup_api_master
	else
		setup_web_directory
		echo "==> skip api setup"
	fi
fi

if [ -n "$DO_START" ]; then
	start_services
else
	echo "==> done; start with: $PROG -l ${MLS_NUM} --role=${ROLE} --start"
fi

print_summary
